IpHelper.cs 1.4 KB

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