我目前有一个服务器应用程序正在侦听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(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);
Allon Guraln.. 6
我不知道UdpClient
,但是如果Socket
直接使用该类,则可以调用该.ReceiveFrom(byte[], ref EndPoint)
方法,并通过第二个参数接收远程地址.
我不知道UdpClient
,但是如果Socket
直接使用该类,则可以调用该.ReceiveFrom(byte[], ref EndPoint)
方法,并通过第二个参数接收远程地址.