首页 文章

在指定网卡上接收udp报文c#

提问于
浏览
2

我有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地址 . 如何才能将这些数据包与他们在两个不同网卡上传入的知识分开?

谢谢 .

3 回答

  • 5

    您没有告诉UdpClient要监听哪个IP endpoints . 即使您要用网卡的 endpoints 替换 IPAddress.Any ,您仍然会遇到同样的问题 .

    如果要告知UdpClient在特定网卡上接收数据包,则必须在构造函数中指定该卡的IP地址 . 像这样:

    var listenEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 2000);
    var myClient = new UdpClient(listenEndpoint);
    

    现在,您可能会问“当我打电话给_902305时, ref endPoint 的部分是什么?”该 endpoints 是客户端的IP endpoints . 我建议用这样的代码替换你的代码:

    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
    }
    

    所以现在你有两个 endpoints :

    • listenEndpoint ,通过构造函数传入,指定要侦听的网卡的地址 .

    • clientEndpoint ,作为ref参数传入Receive(),这将是populated with the client's IP address所以你知道谁在跟你说话 .

  • 1

    看看这个:

    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("");
      }
    

    然后您可以选择开始收听的地址 .

  • 0

    看,如果你按照以下方式创建 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 作为端口传递,而是传递有效的端口号,如果运行此代码并在第一次迭代后中断foreach,则只能创建1 IPEndPoint ,并且可以在调用中使用该代码: myClient.Receive

    请注意 UdpClient 类有一个名为Client的成员,它是一个套接字,尝试探索该对象的属性以及查找一些细节,我找到了我在这里给你的代码:http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx

相关问题