gpt4 book ai didi

c# - 在指定网卡上接收udp数据包c#

转载 作者:行者123 更新时间:2023-11-30 14:12:54 39 4
gpt4 key购买 nike

我有 3 个不同的网卡,每个网卡都有各自的职责。其中两张卡正在接收来自类似设备(直接插入每个单独的网卡)的数据包,该设备在同一端口上发送数据。我需要在保存数据包时知道它们来自哪个设备。

鉴于我需要不指定向我发送数据包的设备的 IP 地址,我如何在给定的网卡上监听?如果需要,我可以为所有 3 个网卡指定一个静态 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 地址。如何在仅知道这些数据包来自两个不同的网卡的情况下分离这些数据包?

谢谢。

最佳答案

您没有告诉 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
}

现在您有两个端点:

  1. listenEndpoint,通过构造函数传入,指定要监听的网卡地址。
  2. clientEndpoint,作为 ref 参数传入 Receive(),将为 populated with the client's IP address所以你知道谁在和你说话。

关于c# - 在指定网卡上接收udp数据包c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15958930/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com