我让用户决定他/她想要连接到哪个网络接口并将其放置在 AppSetting 中。然后我创建一个模块来读取配置文件来决定连接到哪个网络接口,并检查并获取我使用此代码的 IPAddress
在 vb.net 中:
Dim networkinterfaces() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
Dim found As Boolean = False
For Each ni As NetworkInterface In networkinterfaces
If NetworkInterfaceName.Equals(ni.Name) Then
If ni.GetPhysicalAddress().ToString().Length > 0 Then
IPAddressFromNetworkCard = ni.GetIPProperties.UnicastAddresses(0).Address
found = True
Exit For
End If
End If
Next
在 c# 中(更多跟踪,但几乎相同):
Console.WriteLine("Test get ip of interfacecard");
Console.WriteLine("Give name of interfacecard:");
string s = Console.ReadLine();
List<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().ToList<NetworkInterface>();
Console.WriteLine(nics.Count + " networkinterfaces found");
bool found = false;
foreach (NetworkInterface ni in nics)
{
Console.WriteLine("Available nic: " + ni.Name);
}
Console.WriteLine("");
Console.WriteLine(String.Format("searching for: \"{0}\"", s));
foreach (NetworkInterface ni in nics)
{
if (ni.Name.Equals(s))
{
if (ni.GetPhysicalAddress().ToString().Length > 0)
{
Console.WriteLine("Network interface found, ipAddress: " + ni.GetIPProperties().UnicastAddresses[0].Address.ToString());
found = true;
break;
}
}
}
if (!found)
Console.WriteLine(String.Format("\"{0}\" not found", s));
Console.ReadKey();