IpHelper.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. namespace XdCxRhDW.App.Basic
  12. {
  13. public static class IpHelper
  14. {
  15. /// <summary>
  16. /// 获取本地IP
  17. /// </summary>
  18. /// <returns></returns>
  19. public static string GetLocalIp()
  20. {
  21. try
  22. {
  23. string localIP = ConfigurationManager.AppSettings["LocalIP"].Trim();//优先使用本地配置的IP
  24. if(string.IsNullOrWhiteSpace(localIP))
  25. {
  26. using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
  27. {
  28. socket.Connect("8.8.8.8", 65530);
  29. IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
  30. localIP = endPoint.Address.ToString();
  31. }
  32. }
  33. return localIP;
  34. }
  35. catch
  36. {
  37. return "127.0.0.1";
  38. }
  39. }
  40. }
  41. }