I currently have a server application that listens on a port for UDP packets. When one is sent to the server, it receives it correctly and processes it. Is there any way to get the IP address where the packet came from?
This is how I create a 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 OnReceive is called, there is nothing that contains ip where the message came from. I looked through SocketAsyncEventArgs and all I see is listening on 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 OnReceive heres how to get data and information
//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);