c# 获得本地ip地址的三种方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c# 获得本地ip地址的三种方法

波多尔斯基   2020-12-18 我要评论
这篇文章主要介绍了c# 获得本地ip地址的三种方法,帮助大家更好的理解和实用c#,感兴趣的朋友可以了解下

网上有很多种方法可以获取到本地的IP地址。一线常用的有这么些:

枚举本地网卡

using System.Net.NetworkInformation;
using System.Net.Sockets;

foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()
 .Where(a => a.SupportsMulticast)
 .Where(a => a.OperationalStatus == OperationalStatus.Up)
 .Where(a => a.NetworkInterfaceType != NetworkInterfaceType.Loopback)
 .Where(a => a.GetIPProperties().GetIPv4Properties() != null)
 .Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork))
 .Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.IsDnsEligible))
)
{

 Console.WriteLine("Network Interface: {0}", netif.Name);
 IPInterfaceProperties properties = netif.GetIPProperties();
 foreach (IPAddressInformation unicast in properties.UnicastAddresses)
  Console.WriteLine("\tUniCast: {0}", unicast.Address);
}

获得的信息比较全面,相当于网卡的信息都能获取,但是不能区分虚拟网卡(比如docker)。

尝试连接一个IP地址

string localIP;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
 socket.Connect("8.8.8.8", 65530);
 IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
 localIP = endPoint.Address.ToString();
}
Console.WriteLine(localIP);

可以避免虚拟网卡,但是对于内网地址,不一定适用,同时要求网络必须在线,并且有其他服务器可以进行连接。

借用DNS解析

using System.Net;

string sHostName = Dns.GetHostName();
IPHostEntry ipE = Dns.GetHostEntry(sHostName);
IPAddress[] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
 Console.WriteLine("IP Address {0}: {1} ", i, IpA[i].ToString());
}

IPAddress还可以继续通过筛选IPv4的方法进行更精确的选择,和第一种方法是类似的。操作方法非常简洁,但是和获得网卡信息一样,不能区分虚拟网卡。

总结

对于有双网卡的情况,往往两个网卡都是有效的IPV4地址,这个时候需要使用方法2通过局域网或者广域网内访问进行区分。当然也可以选择更为复杂的方式:在局域网内使用广播服务,然后再抓包确定获取的网络地址。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们