在 Internet 上有几个地方向您展示了如何获取 IP 地址。其中很多看起来像这个例子:
String strHostName = string.Empty;
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();
在这个例子中,我获得了多个 IP 地址,但我只对获得路由器分配给运行该程序的计算机的 IP 地址感兴趣:如果某人希望访问共享文件夹,我将提供的 IP 地址例如我的电脑。
如果我没有连接到网络,而是通过没有路由器的调制解调器直接连接到互联网,那么我想得到一个错误。我如何查看我的计算机是否已通过 C# 连接到网络,如果是,则获取 LAN IP 地址。
最佳答案
获取本地IP地址:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
检查您是否已连接:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
关于c# - 获取本地IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803073/