在互联网上有几个地方向您展示如何获得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地址.
我创建了一个winform应用程序,可以使用C#检测,设置和切换IPv4设置.当用户想要从DHCP自动获取IP时,我会调用Automatic_IP():
Automatic_IP:
private void Automatic_IP()
{
ManagementClass mctemp = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moctemp = mctemp.GetInstances();
foreach (ManagementObject motemp in moctemp)
{
if (motemp["Caption"].Equals(_wifi)) //_wifi is the target chipset
{
motemp.InvokeMethod("EnableDHCP", null);
break;
}
}
MessageBox.Show("IP successfully set automatically.","Done!",MessageBoxButtons.OK,MessageBoxIcon.Information);
Getip(); //Gets the current IP address, subnet, DNS etc
Update_current_data(); //Updates the current IP address, subnets etc into a labels
}
Run Code Online (Sandbox Code Playgroud)
在Getip方法中,我提取当前的IP地址,子网,网关和DNS,而不管所有这些都可以由DHCP手动设置或自动分配,并使用该Update_current_data()方法更新标签中的这些值.
Getip:
public bool Getip()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances(); …Run Code Online (Sandbox Code Playgroud)