IPAddressExtensions.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. namespace Masuit.Tools
  7. {
  8. public static class IPAddressExtensions
  9. {
  10. /// <summary>
  11. /// 判断IP是否是私有地址
  12. /// </summary>
  13. /// <param name="myIPAddress"></param>
  14. /// <returns></returns>
  15. public static bool IsPrivateIP(this IPAddress myIPAddress)
  16. {
  17. if (IPAddress.IsLoopback(myIPAddress)) return true;
  18. if (myIPAddress.AddressFamily == AddressFamily.InterNetwork)
  19. {
  20. byte[] ipBytes = myIPAddress.GetAddressBytes();
  21. // 10.0.0.0/24
  22. if (ipBytes[0] == 10)
  23. {
  24. return true;
  25. }
  26. // 169.254.0.0/16
  27. if (ipBytes[0] == 169 && ipBytes[1] == 254)
  28. {
  29. return true;
  30. }
  31. // 172.16.0.0/16
  32. if (ipBytes[0] == 172 && ipBytes[1] == 16)
  33. {
  34. return true;
  35. }
  36. // 192.168.0.0/16
  37. if (ipBytes[0] == 192 && ipBytes[1] == 168)
  38. {
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44. }
  45. }