在互联网上有几个地方向您展示如何获得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();
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我得到了几个IP地址,但我只对获得路由器分配给运行程序的计算机的一个感兴趣:如果他希望访问我计算机中的共享文件夹,我会给某人的IP实例.
如果我没有连接到网络,我通过没有路由器的调制解调器直接连接到互联网,那么我想得到一个错误.如何查看我的计算机是否通过C#连接到网络,以及是否要获取LAN IP地址.