c# .net获取本地计算机IP

using System;
using System.Linq;
using System.Configuration;
using System.Net;

private static string _IpAddress;
public static bool ApiServerOnline
{
  get
    {
      try
        {
          Uri srvUri = new Uri(_ApiServerAdress);
          System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
          c.Connect(srvUri.Host, srvUri.Port);
          string ss = c.Client.LocalEndPoint.ToString();
          IPAddress addr = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address;

          if (addr.IsIPv4MappedToIPv6)
          addr = addr.MapToIPv4();
          _IpAddress = addr.ToString();
          if (_IpAddress == "::1")
            {
              _IpAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(p => p.AddressFamily.ToString() == "InterNetwork")?.ToString();
            }
          c.Close();
          c.Dispose();
          return true;
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.ToString());
        }
        return false;
    }
}

posted @ 2021-03-30 08:35  那一抹的温柔  阅读(200)  评论(0)    收藏  举报