问题
Hej All, I've an application that listens on a socket. The problem is that the pc has 2 network cards and is connected to the company netork and a plc network of course we have to listen/bind/... onto the IPAdress we got from the DHCP in the company network.
But when we do this:
System.Net.IPEndPoint(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0)
We get the IP of the PLC network. Now we are looking for a way to find dynamically the right IPAdress. I got already the tip that you can bind a socket to the IPAdress (0:0:0:0) but we think it's a bit risky to do so.
Has anyone some ideas to solve this issue or some remarks about the 0:0:0:0?
Thanks in advance.
Jonathan
回答1:
The only risk in binding to 0.0.0.0, or leaving it as the default, is that you will accept connections via both networks. Only you know whether that is a risk, i.e. whether there are things in the other network that you don't want connecting to you. Binding to 0.0.0.0, aka INADDR_ANY, is the default and near-universal practice in network programming.
回答2:
Can't you loop through all adresses and use the one which is NOT 0.* and 168.* (or whatever the dhcp delivers...)
That should do in most(!) cases.
回答3:
I let the user decide to what networkinterface he/she wanted to connect to and placed that in an AppSetting. Then I create a module that reads the config file to decide what networkinterface to connect to, and to check and get the IPAddress I use this code
in 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
in c# (some more tracing, but it almost does the same):
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();
来源:https://stackoverflow.com/questions/5143346/get-right-ip-adress-of-pc-with-multiple-network-cards