从 UDP 连接获取客户端 IP C#

发布于 2024-10-13 02:36:08 字数 2194 浏览 3 评论 0原文

我目前有一个服务器应用程序正在侦听端口上的 UDP 数据包。当发送到服务器时,服务器会正​​确接收并处理它。有什么方法可以获取数据包来源的 IP 地址吗?

以下是我创建套接字的方法

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

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, Port);
this.UDPListener.Bind(endPoint);

SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs(); 
socketEventArgs.SetBuffer(this.ReceiveBuffer, 0, this.ReceiveBuffer.Length);
socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
if (!this.UDPListener.ReceiveAsync(socketEventArgs))
    ThreadPool.QueueUserWorkItem(new WaitCallback((Object o) => this.OnReceive(this, socketEventArgs)));

,当调用 OnReceive 时,没有任何内容包含消息来自的 ip。我查看了 SocketAsyncEventArgs,我看到的只是监听 ip。

编辑:

这就是我最终所做的。

this.UDPListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.UDPListener.Bind(new IPEndPoint(IPAddress.Any, Port));

EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
this.UDPListener.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, OnReceive, this.UDPListener);

然后在 OnReceive 中如何获取数据和信息

//Get the received message.
Socket receiveSocket = (Socket)AsyncResult.AsyncState;
EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
int udpMessageLength = receiveSocket.EndReceiveFrom(AsyncResult, ref clientEndPoint);
byte[] udpMessage = new byte[udpMessageLength];
Array.Copy(ReceiveBuffer, udpMessage, udpMessageLength);

//Start listening for a new message.
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, Int32.Parse(((IPEndPoint)receiveSocket.LocalEndPoint).Port.ToString()));
this.UDPListener.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, OnReceive, this.UDPListener);

//Handle the received message
Debug.WriteLine("Recieved {0} bytes from {1}:{2} to {3}:{4}", udpMessageLength, ((IPEndPoint)clientEndPoint).Address, ((IPEndPoint)clientEndPoint).Port, ((IPEndPoint)receiveSocket.LocalEndPoint).Address, ((IPEndPoint)receiveSocket.LocalEndPoint).Port);

I currently have a server application that is listening on a port for UDP packets. When one is sent to the server, it receives it properly and processes it. Is there any way I can get the ip address of where the packet came from?

Here is how I create the socket

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

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, Port);
this.UDPListener.Bind(endPoint);

SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs(); 
socketEventArgs.SetBuffer(this.ReceiveBuffer, 0, this.ReceiveBuffer.Length);
socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
if (!this.UDPListener.ReceiveAsync(socketEventArgs))
    ThreadPool.QueueUserWorkItem(new WaitCallback((Object o) => this.OnReceive(this, socketEventArgs)));

When the OnReceive is called there is nothing that contains the ip where the message came from. I haved looked through the SocketAsyncEventArgs and all I see is the listening ip.

Edit:

Here is what I ended up doing.

this.UDPListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.UDPListener.Bind(new IPEndPoint(IPAddress.Any, Port));

EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
this.UDPListener.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, OnReceive, this.UDPListener);

Then in the OnReceive heres how to get the data and info

//Get the received message.
Socket receiveSocket = (Socket)AsyncResult.AsyncState;
EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
int udpMessageLength = receiveSocket.EndReceiveFrom(AsyncResult, ref clientEndPoint);
byte[] udpMessage = new byte[udpMessageLength];
Array.Copy(ReceiveBuffer, udpMessage, udpMessageLength);

//Start listening for a new message.
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, Int32.Parse(((IPEndPoint)receiveSocket.LocalEndPoint).Port.ToString()));
this.UDPListener.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, OnReceive, this.UDPListener);

//Handle the received message
Debug.WriteLine("Recieved {0} bytes from {1}:{2} to {3}:{4}", udpMessageLength, ((IPEndPoint)clientEndPoint).Address, ((IPEndPoint)clientEndPoint).Port, ((IPEndPoint)receiveSocket.LocalEndPoint).Address, ((IPEndPoint)receiveSocket.LocalEndPoint).Port);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你对谁都笑 2024-10-20 02:36:08

我不知道UdpClient,但是如果你直接使用Socket类,你可以调用.ReceiveFrom(byte[], ref EndPoint) 方法,并通过第二个参数接收远程地址。

I don't know about UdpClient, but if you use the Socket class directly, you can call the .ReceiveFrom(byte[], ref EndPoint) method, and receive the remote address via the second argument.

丢了幸福的猪 2024-10-20 02:36:08

您需要检查参数中的 ReceiveMessageFromPacketInfo 字段。

    void OnReceive(object sender, SocketAsyncEventArgs e)
    {
        var info = e.ReceiveMessageFromPacketInfo;
        byte[] address = info.Address.GetAddressBytes();
    }

You need to inspect the ReceiveMessageFromPacketInfo field in the arguments.

    void OnReceive(object sender, SocketAsyncEventArgs e)
    {
        var info = e.ReceiveMessageFromPacketInfo;
        byte[] address = info.Address.GetAddressBytes();
    }
盛夏尉蓝 2024-10-20 02:36:08

根据 http://msdn.microsoft.com /en-us/library/system.net.sockets.socketasynceventargs.remoteendpoint.aspx SocketAsyncEventArgs 包含一个包含另一端的 RemoteEndPoint 属性。里面有什么东西吗?

According to http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.remoteendpoint.aspx the SocketAsyncEventArgs contains a RemoteEndPoint property that contains the other end. Is there anything in there?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文