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

时间:2011-01-20 21:09:49

标签: c# sockets udp

我目前有一个服务器应用程序正在侦听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);

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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