我有3个不同的网卡,每个网卡都有各自的职责。其中两个网卡正在接收来自类似设备的数据包(直接插入每个单独的网卡),该设备在同一端口上发送数据。我需要保存数据包,知道它们来自哪个设备。
如果要求我不指定发送数据包的设备的ip地址,我如何在给定的网卡上侦听?如果需要,我可以为所有3个nics指定静态ip地址。
示例: nic1 = 169.254.0.27,nic2 = 169.254.0.28,nic3 = 169.254.0.29
现在,我让它接收来自nic1和nic2的数据,而不知道它来自哪个设备。
var myClient = new UdpClient(2000) //Port is random example
var endPoint = new IPEndPoint(IPAddress.Any, 0):
while (!finished)
{
byte[] receivedBytes = myClient.Receive(ref endPoint);
doStuff(receivedBytes);
}我似乎无法指定网卡的静态ip地址,使我无法仅捕获来自其中一个设备的数据包。如果只知道这些数据包来自两个不同的网卡,我如何才能将它们分开?
谢谢。
发布于 2013-04-12 06:19:14
您没有告诉UdpClient要侦听哪个IP端点。即使您将IPAddress.Any替换为您的网卡的端点,您仍然会遇到相同的问题。
如果要告诉UdpClient在特定网卡上接收数据包,则必须在构造函数中指定该卡的IP地址。如下所示:
var listenEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 2000);
var myClient = new UdpClient(listenEndpoint);现在,您可能会问“当我调用myClient.Receive(ref endPoint)时,ref endPoint部分是用来做什么的?”该端点是客户端的IP端点。我建议用下面这样的代码替换你的代码:
IPEndpoint clientEndpoint = null;
while (!finished)
{
var receivedBytes = myClient.Receive(ref clientEndpoint);
// clientEndpoint is no longer null - it is now populated
// with the IP address of the client that just sent you data
}因此,现在您有两个端点:
listenEndpoint,通过构造函数传入,指定要侦听的网卡的地址,并作为on.clientEndpoint,()的populated with the client's IP address参数传入,该参数将为populated with the client's IP address,这样您就可以知道谁在与您交谈。发布于 2013-04-12 05:25:53
看看这个:
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine("Name: " + netInterface.Name);
Console.WriteLine("Description: " + netInterface.Description);
Console.WriteLine("Addresses: ");
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
{
Console.WriteLine(" " + addr.Address.ToString());
}
Console.WriteLine("");
}然后,您可以选择开始侦听的地址。
发布于 2013-04-12 05:37:31
看,如果你用下面的方式创建你的IPEndPoint,它必须工作:
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
...尽量不要将0作为端口而是有效的端口号进行传递,如果您运行此代码并在第一次迭代后中断IPEndPoint,那么您将只创建1个端口,并且可以在调用myClient.Receive时使用它:
注意,UdpClient类有一个名为d Client的成员,它是一个套接字,请尝试探索该对象的属性以找出一些细节,我已经在这里找到了我给您的代码:http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx
https://stackoverflow.com/questions/15958930
复制相似问题