title: Getting client ip from UDP connection C#
body: <p>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?</p>
  
  <p>Here is how I create the socket</p>
  
  <pre><code>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&lt;SocketAsyncEventArgs&gt;(OnReceive);
  if (!this.UDPListener.ReceiveAsync(socketEventArgs))
      ThreadPool.QueueUserWorkItem(new WaitCallback((Object o) =&gt; this.OnReceive(this, socketEventArgs)));
  </code></pre>
  
  <p>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.</p>
  
  <p>Edit:</p>
  
  <p>Here is what I ended up doing.</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>Then in the OnReceive heres how to get the data and info</p>
  
  <pre><code>//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);
  </code></pre>