0

大家好,我有一个侦听套接字的应用程序。问题是 pc 有 2 个网卡并连接到公司 netork 和 plc 网络,当然我们必须监听/绑定/...到我们从公司网络中的 DHCP 获得的 IPAdress。

但是当我们这样做时:

System.Net.IPEndPoint(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0)

我们得到PLC网络的IP。现在我们正在寻找一种动态查找正确IPAdress 的方法。我已经得到提示,您可以将套接字绑定到 IPAdress (0:0:0:0),但我们认为这样做有点冒险。

有没有人有一些想法来解决这个问题或关于 0:0:0:0 的一些评论?

提前致谢。

乔纳森

4

3 回答 3

1

绑定到 0.0.0.0 或将其保留为默认值的唯一风险是您将接受通过两个网络的连接。只有您知道是否有风险,即其他网络中是否有您不想连接到您的东西。绑定到 0.0.0.0,也就是 INADDR_ANY,是网络编程中的默认和近乎普遍的做法。

于 2011-02-28T22:40:53.947 回答
0

您不能遍历所有地址并使用不是 0.* 和 168.* 的地址(或 dhcp 提供的任何地址...)

在大多数(!)情况下应该这样做。

于 2011-02-28T14:40:42.117 回答
0

我让用户决定他/她想要连接到哪个网络接口并将其放置在 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();
于 2011-03-16T08:27:06.227 回答