Files
shadowsocks-windows/shadowsocks-csharp/Util/SocketUtil.cs
T
noisyfox 53ce1948e4 Unified ipv4, ipv6 and domain connections.
-Use dual-mode socket & DnsEndPoint to handle all domain name connection.
-Move all socket creation into one single function.

So that we could treat domain name just like ipv4 & ipv6 address.
This also solves the async domain solving problem because the os will
hanlde it for us.
2016-08-16 20:40:09 +10:00

67 lines
1.9 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
namespace Shadowsocks.Util
{
public static class SocketUtil
{
private class DnsEndPoint2 : DnsEndPoint
{
public DnsEndPoint2(string host, int port) : base(host, port)
{
}
public DnsEndPoint2(string host, int port, AddressFamily addressFamily) : base(host, port, addressFamily)
{
}
public override string ToString()
{
return this.Host + ":" + this.Port;
}
}
public static EndPoint GetEndPoint(string host, int port)
{
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(host, out ipAddress);
if (parsed)
{
return new IPEndPoint(ipAddress, port);
}
// maybe is a domain name
return new DnsEndPoint2(host, port);
}
public static Socket CreateSocket(EndPoint endPoint, ProtocolType protocolType = ProtocolType.Tcp)
{
SocketType socketType;
switch (protocolType)
{
case ProtocolType.Tcp:
socketType = SocketType.Stream;
break;
case ProtocolType.Udp:
socketType = SocketType.Dgram;
break;
default:
throw new NotSupportedException("Protocol " + protocolType + " doesn't supported!");
}
if (endPoint is DnsEndPoint)
{
var socket = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
return socket;
}
else
{
return new Socket(endPoint.AddressFamily, socketType, protocolType);
}
}
}
}