title: How udp works in .net
body: <p>I was told that UDP was connectionless meaning that you could not be sure if the packages would reach the destination. </p>
  
  <p>Why when doing:</p>
  
  <pre><code>var dataToSend = new byte[]{1};
  UdpClient client = new UdpClient();
  client.Send(dataToSend,1,"192.168.0.45", 1234);
  </code></pre>
  
  <p>the variable LocalEndpoint initializes:</p>
  
  <p><img src="https://i.stack.imgur.com/YrxBs.png" alt="enter image description here"></p>
  
  <p>Correct me if I am wrong. I believe that the variable LocalEndPoint was initialized by the router. The reason why I believe that is because every time the server (192.168.0.45) receives data and then replies, I see that data is being send through the port 62446 on the reply.  </p>
  
  <p><strong>So my question is</strong> if I am using the udp protocol why am I getting a response from the router? If I am getting a response from the router then that is not UDP or perhaps I have a wrong understanding of udp. I dont think the port number get's randomly picked. If I have had configure the router to do port forwarding on port 62446 to some other computer then my program will not have had worked. </p>
  
  <hr>
  
  <p><strong>here is the client code:</strong></p>
  
  <pre><code>string ipOfServer = "192.168.0.45";
  int portServerIsListeningOn = 1234;
  
  // send data to server
  Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  IPEndPoint sending_end_point = new IPEndPoint(IPAddress.Parse(ipOfServer), portServerIsListeningOn);
  sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
  
  // after I send data localendpoint gets initialized! and the server always respond through that port!
  
  // get info
  var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
  
  // now wait for server to send data back
  IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
  byte[] buffer = new byte[1024];
  sending_socket.Receive(buffer); // &lt;----- keeps waiting in here :(
  </code></pre>
  
  <p><strong>here is the server code:</strong></p>
  
  <pre><code>// wait for client to send data
  UdpClient listener = new UdpClient(11000);
  IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);        
  byte[] receive_byte_array = listener.Receive(ref groupEP);
  listener.Connect(groupEP);
  
  // reply
  byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
  listener.Send(dataToSend, dataToSend.Length);
  </code></pre>