IpHelper.cs 1.3 KB

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