IpHelper.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. using System.Net.Http;
  12. public static class IpHelper
  13. {
  14. private static string _localIp;
  15. /// <summary>
  16. /// 获取本地IP
  17. /// </summary>
  18. /// <returns></returns>
  19. public static string GetLocalIp()
  20. {
  21. if (!string.IsNullOrWhiteSpace(_localIp))
  22. {
  23. return _localIp;
  24. }
  25. string localIP = null;
  26. try
  27. {
  28. foreach (string item in ConfigurationManager.AppSettings.Keys)
  29. {
  30. if (item == "LocalIP")
  31. {
  32. localIP = ConfigurationManager.AppSettings["LocalIP"].Trim();//优先使用本地配置的IP
  33. }
  34. }
  35. if (!string.IsNullOrWhiteSpace(localIP))
  36. return localIP;
  37. }
  38. catch
  39. {
  40. }
  41. try
  42. {
  43. using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
  44. {
  45. socket.Connect("8.8.8.8", 65530);
  46. IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
  47. localIP = endPoint.Address.ToString();
  48. return localIP;
  49. }
  50. }
  51. catch
  52. {
  53. }
  54. return "127.0.0.1";
  55. }
  56. public static void SetLocalIp(string localIp)
  57. {
  58. _localIp = localIp;
  59. }
  60. }