C# UDP Socket: Get receiver address

前端 未结 5 1627
萌比男神i
萌比男神i 2020-12-29 07:04

I have an asynchronous UDP server class with a socket bound on IPAddress.Any, and I\'d like to know which IPAddress the received packet was sent to (...or received on). It

5条回答
  •  醉梦人生
    2020-12-29 07:32

    Adam

    This is not tested...let's try

    private void DoReceiveFrom(IAsyncResult iar){
    //Get the received message.
    Socket recvSock = (Socket)iar.AsyncState;
    //EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
    Socket clientEP = recvSock.EndAccept(iar);
    int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP);
    byte[] localMsg = new byte[msgLen];
    Array.Copy(buffer, localMsg, msgLen);
    
    //Start listening for a new message.
    EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
    udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock);
    
    //Handle the received message
    /*
    Console.WriteLine("Recieved {0} bytes from {1}:{2} to {3}:{4}",
                      msgLen,
                      ((IPEndPoint)recvSock.RemoteEndPoint).Address,
                      ((IPEndPoint)recvSock.RemoteEndPoint).Port,
                      ((IPEndPoint)recvSock.LocalEndPoint).Address,
                      ((IPEndPoint)recvSock.LocalEndPoint).Port);
    //Do other, more interesting, things with the received message.
    */
    Console.WriteLine("Recieved {0} bytes from {1}:{2} to {3}",
                      msgLen,
                      ((IPEndPoint)recvSock.RemoteEndPoint).Address,
                      ((IPEndPoint)recvSock.RemoteEndPoint).Port,
                      clientEP.RemoteEP.ToString();
     }
    

提交回复
热议问题