title: C# Getting sender address from UDP message
body: <p>I have an embedded Ethernet interface (Lantronix XPort) that responds to a UDP broadcast with its identifying information.</p>
  
  <p>I am able to multicast the "magic packet" and datagrams are received by the listener correctly, however I also need to find out what IP Address send that response datagram. If it were TCP, I would do socket.RemoteEndPoint, but that throws an exception when applied to a UDP socket.</p>
  
  <pre><code>public class Program
  {
      public static void Main(string[] args)
      {
          // magic packet
          byte[] magicPacket = new byte[4] { 0, 0, 0, 0xf6 };
  
          // set up listener for response
          Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  
          // EDIT: Also, had to add this to for it to broadcast correctly
          sendSocket.EnableBroadcast = true;
          IPEndPoint listen_ep = new IPEndPoint(IPAddress.Any, 0);
          sendSocket.Bind(listen_ep);
  
          // set up broadcast message
          EndPoint send_ep = new IPEndPoint(IPAddress.Parse("192.168.255.255"), 30718);
          sendSocket.SendTo(magicPacket, magicPacket.Length, SocketFlags.None, send_ep);
  
          DateTime dtStart = DateTime.Now;
          while (true)
          {
              if (sendSocket.Available &gt; 0)
              {
                  byte[] data = new byte[2048];
                  // throws SocketException
                  //IPEndPoint ip = sendSocket.RemoteEndPoint as IPEndPoint;
                  sendSocket.Receive(data, SocketFlags.None);
                  if (data.Length &gt; 4)
                  {
                      PrintDevice(data);
                  }
              }
  
              if (DateTime.Now &gt; dtStart.AddSeconds(5))
              {
                  break;
              }
  
              Console.WriteLine(".");
  
              Thread.Sleep(100);
          }
  
          // wait for keypress to quit
          Console.WriteLine("Press any key to exit.");
          Console.ReadKey();
      }
  } 
  </code></pre>
  
  <p>Any thoughts? Is there a better strategy to reading the response datagrams that would let me ascertain the Remote IP Address?</p>
  
  <p>EDIT:</p>
  
  <p>As is typical, the minute I post on SO, a moment of clarity hits me.</p>
  
  <p>Turns out I can just do this:</p>
  
  <pre><code>                EndPoint remote_ep = new IPEndPoint(IPAddress.Any, 0);
                  // Use ReceiveFrom instead of Receieve
                  //sendSocket.Receive(data, SocketFlags.None);
                  sendSocket.ReceiveFrom(data, ref remote_ep);
  </code></pre>
  
  <p>And remote_ep now contains the remote endpoint information!</p>