【问题标题】:Obtain UDP Sender IP address on a receiving port that was set to IPAddress.any?在设置为 IPAddress.any 的接收端口上获取 UDP 发件人 IP 地址?
【发布时间】:2019-07-27 10:34:09
【问题描述】:

我有一个应用程序,我需要从任何 IP 地址(在特定端口上)接收 UDP 单播数据包,但想知道接收数据包的发件人 IP 地址。我创建了一个套接字并通过以下代码绑定它:

Socket SocketLocal;
EndPoint epReceive;
int UCPort = 1000;
byte[] Buffer = new byte[1500];

SocketLocal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

SocketLocal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

// Bind Socket
epReceive = new IPEndPoint(IPAddress.Any, UCPort );
SocketLocal.Bind(epReceive);

SocketLocal.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref epReceive, new AsyncCallback(RxCallBack), Buffer);

回调看起来像:

public void RxCallBack(IAsyncResult aResult)
{
    try
    {
        byte[] receivedData = new byte[1500];

        receivedData = (byte[])aResult.AsyncState;

        // I process/intepret the received data
        // ...

        // I have a list box where I simply want to display
        // the sender's IP address
        lstBox.Items.Add(SocketLocal.LocalEndPoint.ToString()));
        //  Here I simply get 0.0.0.0:<port number>
        // If I modify SocketLocal.LocalEndPoint.ToString above to SocketLocal.RemoteEndPoint.ToString it throws an exception

        Buffer = new byte[1500];
        SocketLocal.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref epReceive, new AsyncCallback(RxCallBack), Buffer);

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

}  // End of RxCallBack

这很好用,因为我能够接收从任何 IP 发送到我的计算机的数据。但是,我想知道发件人的 IP 地址。

当我尝试提取发件人的 IP 地址时,我只得到“0.0.0.0”,考虑到我将 Socket 设置为 IPAddress.any,这是有道理的

必须有办法找出发件人的 IP 地址。我已经搜索并尝试了所有各种选项,但均无济于事。谁能提供一些指导?

【问题讨论】:

  • “当我尝试提取时”?你是怎么做到的?文档清楚地说明了如何提取远程端点地址docs.microsoft.com/en-us/dotnet/api/…,它适用于大多数用户。
  • Lex 好日子,当套接字未配置为 IpAddress.any 而是特定地址时,您引用的文档工作得非常好。这样做我可以很容易地获得发件人的 IP 地址。当我将套接字配置为 IPAddress.any 时,生成的发件人的 IP 返回为 0.0.0.0。这就是问题所在......我需要一个可以从任何 IP 地址接收的套接字,但是,当我收到数据时,我想知道是哪个 IP 发送的。
  • 在您的问题中,epReceiveepRemote 应该是两个不同的变量吗?此外,您还遗漏了错误的代码部分;如果您不发布完整的问题,没有人可以提供帮助。
  • 晚安,Ben,对不起,我只是复制了一部分代码并错误地编辑了它。我可以添加更多代码,但我只是在检查是否可以通过 IPAddress.any 参数绑定端口来获取发件人的 IP 地址,
  • 但是导致错误结果的代码在哪里?它必须在BeginReceiveFrom 的回调中,因为每个传入数据包都带有发送者地址;你不可能在绑定后立即知道它。

标签: c# udp


【解决方案1】:

在查看了每个人的 cmets 后,我找到了问题的答案。这里有一个类似的问题:

C# UDP Socket: Get receiver address

回顾这个问题,我使用了其中的一部分,并能够为我的原始问题创建一个解决方案。生成的代码附加到我上面列出的原始问题和下面的列表中:

作为后续... C Gonzales 的评论让我以不同的方式看待这个问题,因此我能够通过以下方式解决我的问题。首先,我将“BeginReceiveFrom”方法的最终参数(状态)修改为实际的套接字。这会影响传递给回调函数的“IAsyncResult”项。现在我的第一部分软件看起来像这样:

// Just the BeginReceiveFrom was changed
SocketLocal.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref epReceive, new AsyncCallback(RxCallBack), SocketLocal);

接下来我将调用改回如下:

public void RxCallBack(IAsyncResult aResult)
{
    try
    {
            // Create Local Buffer
            byte[] receivedData = new byte[1500];

            // Create Socket to get received data
            Socket ReceiveSocket = (Socket)aResult.AsyncState;

            // Create Endpoint
            EndPoint epReceive = new IPEndPoint(IPAddress.Any, 0);

            // Extract Data...
            int UDPRxDataLength = ReceiveSocket.EndReceiveFrom(aResult, ref epReceive);

            // Copy Rx Data to Local Buffer
            Array.Copy(SocketLocal.Buffer, receivedData, UDPRxDataLength);

            //Start listening for a new message.

            // Setup for next Packet to be received
            Buffer = new byte[1500];
            SocketLocal.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref epReceive, (RxCallBack), SocketLocal);

        // I process/intepret the received data
        // ...

        // The Sender's IP Address is located in the epReceive Endpoint
        lstBox.Items.Add( "Sender IP " + ((IPEndPoint)epReceive).Address.ToString() );

    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.ToString());
    }


}  // End of RxCallBack

做到以上几点就完美了!

感谢大家的cmets!

【讨论】:

  • 感谢您发布解决问题的代码。但是,您应该从问题中删除代码并将其发布在此答案中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多