Get client IP address from UDP packets received with UdpClient

I am developing a multi-player action game using the System.Net.Sockets.UdpClient class .

This is for two players, so you need to open the server and wait for incoming connections. Another player enters the host's IP address and tries to send a ping to make sure that a connection is possible and there is an open server. The host then responds with "pong."

Once the game is running, both should send udp messages to each other, so they both need the opponents ip address.

Of course, the server can also enter the IP addresses of clients, but for me this seems unnecessary.

How can I get the client IP address from the udp packet when a ping message is received?

Here is my receive code (server is waiting for ping):

    private void ListenForPing()
    {
        while (!closeEverything)
        {
             var deserializer = new ASCIIEncoding();
             IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
             byte[] recData = udp.Receive(ref anyIP);
             string ping = deserializer.GetString(recData);
             if (ping == "ping")
             {
                 Console.WriteLine("Ping received.");
                 InvokePingReceiveEvent();
             }
        }
    }
+3
2

, , anyIP IPEndPoint .

+12
private void ListenForPing()
{
    while (!closeEverything)
    {

         IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
         byte[] recData = udp.Receive(ref anyIP);
         string ping = Encoding.ASCII.GetString(recData);
         if (ping == "ping")
         {
             Console.WriteLine("Ping received.");
             Console.WriteLine("Ping was sent from " + anyIP.Address.ToString() +
                             " on their port number " + anyIP.Port.ToString());
             InvokePingReceiveEvent();
         }
    }
}

http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx

+5

All Articles