Skip to content

Commit

Permalink
Support ipv6
Browse files Browse the repository at this point in the history
  • Loading branch information
shigenobu committed Apr 15, 2024
1 parent 3bbd9f6 commit c61d3fe
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 13 deletions.
14 changes: 8 additions & 6 deletions OrangeCabinet.Tests/TestSimple.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public TestSimple(ITestOutputHelper testOutputHelper)
OcDate.AddSeconds = 60 * 60 * 9;
// OcLogger.Writer = new StreamWriter(new FileStream("Test.log", FileMode.Append));
OcLogger.Verbose = true;
// OcLogger.Transfer = new OcLoggerTransfer
// {
// Transfer = msg => testOutputHelper.WriteLine(msg.ToString()),
// Raw = false
// };
OcLogger.Transfer = new OcLoggerTransfer
{
Transfer = msg => testOutputHelper.WriteLine(msg.ToString()),
Raw = false
};
}

[Fact]
Expand Down Expand Up @@ -45,8 +45,10 @@ public void Test()

// ...
Thread.Sleep(1000);
server.SendTo("hello from server", IPEndPoint.Parse("127.0.0.1:18710"));
server.SendTo("hello from server", new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8710));
server.Shutdown();

OcLogger.Close();
}
}

Expand Down
87 changes: 87 additions & 0 deletions OrangeCabinet.Tests/TestSimpleV6.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System.IO;
using System.Net;
using System.Threading;
using Xunit;
using Xunit.Abstractions;

namespace OrangeCabinet.Tests
{
public class TestSimpleV6
{
public TestSimpleV6(ITestOutputHelper testOutputHelper)
{
OcDate.AddSeconds = 60 * 60 * 9;
// OcLogger.Writer = new StreamWriter(new FileStream("Test.log", FileMode.Append));
OcLogger.Verbose = true;
OcLogger.Transfer = new OcLoggerTransfer
{
Transfer = msg => testOutputHelper.WriteLine(msg.ToString()),
Raw = false
};
}

[Fact]
public void Test()
{
var serverBinder = new OcBinder(new SampleV6Callback())
{
SocketAddressFamily = OcSocketAddressFamily.Ipv6,
BindPort = 8710,
};
var server = new OcLocal(serverBinder);
server.Start();
// server.WaitFor();

// -----
using var clientBinder = new OcBinder(new SampleV6Callback())
{
SocketAddressFamily = OcSocketAddressFamily.Ipv6,
BindPort = 18710,
};
var client = new OcRemote(clientBinder, "::1", 8710);
for (int j = 0; j < 3; j++)
{
client.Send($"{j}".OxToBytes());
}
// -----

// ...
Thread.Sleep(1000);
server.SendTo("hello from server", new IPEndPoint(IPAddress.Parse("::1"), 8710));
server.Shutdown();

OcLogger.Close();
}
}

public class SampleV6Callback : OcCallback
{
private const string Key = "inc";

public override void Incoming(OcRemote remote, byte[] message)
{
OcLogger.Info($"Received: {message.OxToString()} ({remote})");

int inc = remote.GetValue<int>(Key);
inc++;
remote.SetValue(Key, inc);

remote.Send($"{inc}".OxToBytes());
if (inc > 10)
{
remote.ClearValue(Key);
remote.Escape();
}
}

public override void Timeout(OcRemote remote)
{
OcLogger.Info($"Timeout: {remote}");
}

public override void Shutdown(OcRemote remote)
{
OcLogger.Info($"Shutdown: {remote}");
}
}
}
35 changes: 33 additions & 2 deletions OrangeCabinet/OcBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ namespace OrangeCabinet;
/// </summary>
public class OcBinder : IDisposable
{
/// <summary>
/// Default ip v4 host.
/// </summary>
private const string DefaultIpv4Host = "0.0.0.0";

/// <summary>
/// Default ip v6 host.
/// </summary>
private const string DefaultIpv6Host = "::";

/// <summary>
/// Receive handler.
/// </summary>
Expand All @@ -32,10 +42,15 @@ public OcBinder(OcCallback callback)
/// </summary>
internal OcCallback Callback { get; }

/// <summary>
/// Address family, default ipv4.
/// </summary>
public OcSocketAddressFamily SocketAddressFamily { get; init; } = OcSocketAddressFamily.Ipv4;

/// <summary>
/// Bind host, default 0.0.0.0.
/// </summary>
public string BindHost { get; init; } = "0.0.0.0";
public string BindHost { get; set; } = DefaultIpv4Host;

/// <summary>
/// Bind port, default random between 18000-28999.
Expand Down Expand Up @@ -80,9 +95,25 @@ internal void Bind(OcBindMode bindMode)

try
{
// check v6
if (SocketAddressFamily == OcSocketAddressFamily.Ipv6 &&
IPAddress.Parse(BindHost).AddressFamily == AddressFamily.InterNetwork &&
BindHost.Equals(DefaultIpv4Host))
{
BindHost = DefaultIpv6Host;
OcLogger.Info($"Change host from '{DefaultIpv4Host}' to '{DefaultIpv6Host}', so ipv6 is adapted");
}

// init
BindSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
BindSocket = new Socket(OcSocketAddressFamilyResolver.Resolve(SocketAddressFamily), SocketType.Dgram,
ProtocolType.Udp);
BindSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
if (SocketAddressFamily == OcSocketAddressFamily.Ipv6)
{
BindSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
OcLogger.Info("Ipv4 socket is treated as ipv6 socket");
}

BindSocket.Bind(new IPEndPoint(IPAddress.Parse(BindHost), BindPort));
BindSocket.Blocking = false;

Expand Down
5 changes: 1 addition & 4 deletions OrangeCabinet/OcRemote.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,7 @@ public void Send(byte[] message)

try
{
lock (this)
{
_binder.SendTo(message, RemoteEndpoint);
}
_binder.SendTo(message, RemoteEndpoint);
}
catch (Exception e)
{
Expand Down
40 changes: 40 additions & 0 deletions OrangeCabinet/OcSocketAddressFamily.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.Net.Sockets;

namespace OrangeCabinet;

/// <summary>
/// Address family.
/// </summary>
public enum OcSocketAddressFamily
{
/// <summary>
/// Ipv4.
/// </summary>
Ipv4,

/// <summary>
/// Ipv6.
/// If selected, v4 socket is treated as v6 socket.
/// </summary>
Ipv6
}

/// <summary>
/// Address family resolver.
/// </summary>
internal static class OcSocketAddressFamilyResolver
{
/// <summary>
/// Resolve for 'AddressFamily' .
/// </summary>
/// <param name="socketAddressFamily">address family</param>
/// <returns>AddressFamily</returns>
internal static AddressFamily Resolve(OcSocketAddressFamily socketAddressFamily)
{
return socketAddressFamily switch
{
OcSocketAddressFamily.Ipv6 => AddressFamily.InterNetworkV6,
_ => AddressFamily.InterNetwork
};
}
}
2 changes: 1 addition & 1 deletion OrangeCabinet/OcUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ internal static int RandomInt(int min, int max)
}
catch (Exception e)
{
OcLogger.Debug(() => e);
// ignored
}

return default;
Expand Down

0 comments on commit c61d3fe

Please sign in to comment.