/TCPingInfoViewLib/NetUtils/IPFormatter.cs

https://github.com/HMBSbige/TCPingInfoView · C# · 100 lines · 89 code · 9 blank · 2 comment · 20 complexity · 534cad2f53743cbeff9c914a7c7eeee0 MD5 · raw file

  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Numerics;
  5. using System.Text.RegularExpressions;
  6. namespace TCPingInfoViewLib.NetUtils
  7. {
  8. public static class IPFormatter
  9. {
  10. public static readonly Regex EndPointRegexStr = new Regex(@"^\[(.*)\]:(\d{1,5})|(.*):(\d{1,5})$");
  11. public static bool IsIPAddress(string input)
  12. {
  13. return IPAddress.TryParse(input, out _);
  14. }
  15. public static bool IsPort(int port)
  16. {
  17. if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort)
  18. {
  19. return true;
  20. }
  21. return false;
  22. }
  23. public static IPEndPoint ToIPEndPoint(string str, int defaultPort = 443)
  24. {
  25. if (string.IsNullOrWhiteSpace(str) || !IsPort(defaultPort))
  26. {
  27. return null;
  28. }
  29. var sp = EndPointRegexStr.Match(str).Groups;
  30. if (sp.Count == 5)
  31. {
  32. var hostname = string.IsNullOrWhiteSpace(sp[1].Value) ? sp[3].Value : sp[1].Value;
  33. if (IPAddress.TryParse(hostname, out var ip))
  34. {
  35. if (int.TryParse(string.IsNullOrWhiteSpace(sp[2].Value) ? sp[4].Value : sp[2].Value, out var port))
  36. {
  37. if (IsPort(port))
  38. {
  39. return new IPEndPoint(ip, port);
  40. }
  41. }
  42. }
  43. }
  44. else if (sp.Count == 1)
  45. {
  46. var groups = Regex.Match(str, @"^\[(.*)\]$").Groups;
  47. if (groups.Count == 2)
  48. {
  49. if (IPAddress.TryParse(groups[1].Value, out var ip))
  50. {
  51. return new IPEndPoint(ip, defaultPort);
  52. }
  53. }
  54. else
  55. {
  56. if (IPAddress.TryParse(str, out var ip))
  57. {
  58. return new IPEndPoint(ip, defaultPort);
  59. }
  60. }
  61. }
  62. return null;
  63. }
  64. public static BigInteger ToInteger(this IPAddress ip)
  65. {
  66. if (ip != null)
  67. {
  68. var bytes = ip.GetAddressBytes();
  69. if (BitConverter.IsLittleEndian)
  70. {
  71. bytes = bytes.Reverse().ToArray();
  72. }
  73. BigInteger res;
  74. if (bytes.Length > 8)
  75. {
  76. //IPv6
  77. res = BitConverter.ToUInt64(bytes, 8);
  78. res <<= 64;
  79. res += BitConverter.ToUInt64(bytes, 0);
  80. }
  81. else
  82. {
  83. //IPv4
  84. res = BitConverter.ToUInt32(bytes, 0);
  85. }
  86. return res;
  87. }
  88. return 0;
  89. }
  90. }
  91. }