IpAddress.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Common
  8. {
  9. public class IpAddress
  10. {
  11. private static string ip = "";
  12. public static string getIp
  13. {
  14. get
  15. {
  16. try
  17. {
  18. if (ip == "" || ip == null)
  19. {
  20. IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
  21. IPAddress ipAddr = ipHost.AddressList[0];
  22. ip = ipAddr.ToString();
  23. }
  24. }
  25. catch (Exception ex)
  26. { }
  27. return ip;
  28. }
  29. }
  30. #region 单例获取值
  31. /*
  32. private IpAddress()
  33. {
  34. }
  35. private static IpAddress ipAddress;
  36. // 定义一个标识确保线程同步
  37. private static readonly object locker = new object();
  38. public static IpAddress GetInstance()
  39. {
  40. if (ipAddress == null)
  41. {
  42. lock (locker)
  43. {
  44. if (ipAddress == null)
  45. {
  46. ipAddress = new IpAddress();
  47. IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
  48. IPAddress ipAddr = ipHost.AddressList[0];
  49. getIp = ipAddr.ToString();
  50. }
  51. }
  52. }
  53. return ipAddress;
  54. }
  55. //*/
  56. #endregion
  57. }
  58. }