You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SocketUtil.cs 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. namespace Shadowsocks.Util
  5. {
  6. public static class SocketUtil
  7. {
  8. private class DnsEndPoint2 : DnsEndPoint
  9. {
  10. public DnsEndPoint2(string host, int port) : base(host, port)
  11. {
  12. }
  13. public DnsEndPoint2(string host, int port, AddressFamily addressFamily) : base(host, port, addressFamily)
  14. {
  15. }
  16. public override string ToString()
  17. {
  18. return this.Host + ":" + this.Port;
  19. }
  20. }
  21. public static EndPoint GetEndPoint(string host, int port)
  22. {
  23. IPAddress ipAddress;
  24. bool parsed = IPAddress.TryParse(host, out ipAddress);
  25. if (parsed)
  26. {
  27. return new IPEndPoint(ipAddress, port);
  28. }
  29. // maybe is a domain name
  30. return new DnsEndPoint2(host, port);
  31. }
  32. public static Socket CreateSocket(EndPoint endPoint, ProtocolType protocolType = ProtocolType.Tcp)
  33. {
  34. SocketType socketType;
  35. switch (protocolType)
  36. {
  37. case ProtocolType.Tcp:
  38. socketType = SocketType.Stream;
  39. break;
  40. case ProtocolType.Udp:
  41. socketType = SocketType.Dgram;
  42. break;
  43. default:
  44. throw new NotSupportedException("Protocol " + protocolType + " doesn't supported!");
  45. }
  46. if (endPoint is DnsEndPoint)
  47. {
  48. var socket = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
  49. socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
  50. return socket;
  51. }
  52. else
  53. {
  54. return new Socket(endPoint.AddressFamily, socketType, protocolType);
  55. }
  56. }
  57. }
  58. }