/// <summary>
/// C# 如何获取本地IP
/// </summary>
/// <returns></returns>
public void GetLocalIP()
{
List<string> strIPs = new List<string>();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
var mac = adapter.GetPhysicalAddress(); Console.WriteLine(mac);
IPInterfaceProperties ip = adapter.GetIPProperties();
UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
//GatewayIPAddressInformationCollection ipv4Collection = ip.GatewayAddresses;
//Debug.LogError("ipv4Collection>>>>> " + ipv4Collection.ToString());
foreach (UnicastIPAddressInformation ipadd in ipCollection)
{
Debug.LogError(">>>>> " + ipadd.Address.ToString());
//InterNetwork IPV4地址
if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{ //判断是否为ipv4
Debug.LogError("本机ipv4: " + ipadd.Address.ToString());
strIPs.Add(ipadd.Address.ToString());
}
//InterNetworkV6 IPV6地址
if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{ //判断是否为ipv6
Debug.LogError("本机ipv6: " + ipadd.Address.ToString());
strIPs.Add(ipadd.Address.ToString());
}
}
}
}
}
C# 关于如何获取本地IP问题
最新推荐文章于 2025-02-12 09:01:51 发布
本文介绍了一种使用C#语言来获取计算机本地IP地址的方法。通过遍历所有网络接口并筛选出以太网类型的接口,进而获取其IPv4和IPv6地址。适用于需要在网络应用程序中快速识别本机IP地址的场景。
5540

被折叠的 条评论
为什么被折叠?



