IpHelper.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Net.NetworkInformation;
  9. using System.Runtime.InteropServices;
  10. using System.Configuration;
  11. public static class IpHelper
  12. {
  13. /// <summary>
  14. /// 获取本地IP
  15. /// </summary>
  16. /// <returns></returns>
  17. public static string GetLocalIp()
  18. {
  19. string localIP = null;
  20. try
  21. {
  22. foreach (string item in ConfigurationManager.AppSettings.Keys)
  23. {
  24. if (item == "LocalIP")
  25. {
  26. localIP = ConfigurationManager.AppSettings["LocalIP"].Trim();//优先使用本地配置的IP
  27. }
  28. }
  29. if (!string.IsNullOrWhiteSpace(localIP))
  30. return localIP;
  31. }
  32. catch
  33. {
  34. }
  35. try
  36. {
  37. using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
  38. {
  39. socket.Connect("8.8.8.8", 65530);
  40. IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
  41. localIP = endPoint.Address.ToString();
  42. return localIP;
  43. }
  44. }
  45. catch
  46. {
  47. }
  48. return "127.0.0.1";
  49. }
  50. }