我尝试获取我的本地 IP,下面的代码向您展示了我是如何做到的。
问题是当我连接到 wifi 并且我的以太网卡未连接时,它会给我一个 169.xxx.xxx.xxx 地址。
如何检查连接了哪个网卡并获取该 IP?
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "127.0.0.1";
}
我用这个:
List<IPAddress> addresses = new List<IPAddress>();
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkItf in networkInterfaces)
{
// check whether turned on
if (networkItf.OperationalStatus == OperationalStatus.Up)
{
// read the IP configuration for each network
IPInterfaceProperties properties = networkItf.GetIPProperties();
// each network interface may have multiple IP addresses
foreach (IPAddressInformation address in properties.UnicastAddresses)
{
// filter only IPv4 addresses, if required...
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
// ignore loopback addresses (e.g., 127.0.0.1)
if (IPAddress.IsLoopback(address.Address))
continue;
// add result
addresses.Add(address.Address);
}
}
}
您可以使用
NetworkInterface
类来查看是否有确实连接的网络接口。请查看此处的相关文档:https://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface(v=vs.110).aspx
此代码片段应该为您提供您感兴趣的结果:
private string GetLocalIP()
{
var isConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (isConnected)
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
}
return "127.0.0.1";
}
这对我有用https://stackoverflow.com/a/27376368/7232036
private 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;
return endPoint.Address.ToString();
}
}
这将给出您正在寻找的 IP 地址
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(ip.Address.ToString());
}
}
}
}