Network.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. namespace Aitex.Core.Utilities
  7. {
  8. public static class Network
  9. {
  10. const string IpPrefix = "192.18.";
  11. static string _localIP;
  12. public static string LocalIP
  13. {
  14. get
  15. {
  16. if (string.IsNullOrWhiteSpace(_localIP))
  17. {
  18. string hostName = Dns.GetHostName();
  19. IPHostEntry me = Dns.GetHostEntry(hostName);
  20. IPAddress[] ips = me.AddressList;
  21. Func<IPAddress, bool> predicateIPV4 = ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork;
  22. Func<IPAddress, bool> predicate192 = ip => predicateIPV4(ip) && ip.ToString().StartsWith(IpPrefix);
  23. _localIP = ips.Any(predicate192) ? ips.First(predicate192).ToString()
  24. : ips.Any(predicateIPV4) ? ips.First(predicateIPV4).ToString()
  25. : (ips.Length > 0 ? ips[0]: new IPAddress(0x0)).ToString();
  26. }
  27. return _localIP;
  28. }
  29. }
  30. }
  31. }