Hej All,我有一个监听套接字的应用程序。 问题是这台电脑有2个网卡,并连接到公司netork和plc网络,当然我们必须监听/绑定/ ...到我们从公司网络的DHCP获得的IP地址。
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.
但是当我们这样做时:
System.Net.IPEndPoint(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0)我们获得了PLC网络的IP。现在我们正在寻找一种动态查找正确的IP地址的方法。我已经得到了一个可以将套接字绑定到IP地址的提示(0:0:0: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.
有没有人想要解决这个问题或有关0:0:0:0的一些评论?
Has anyone some ideas to solve this issue or some remarks about the 0:0:0:0?
提前致谢。
Jonathan
推荐答案我让用户决定他/她想要连接到哪个网络接口并将其放在AppSetting中。然后我创建一个模块来读取配置文件以决定要连接的网络接口to,以及检查和获取IPAddress我在vb中使用此代码
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
:
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();更多推荐
使用多个网卡获取正确的IP地址
发布评论