Udp Socket IPEndPoint返回0.0.0.0:0

时间:2013-03-15 11:45:43

标签: sockets c#-4.0 udp

我的代码用C#我收到数据HeartBeat。我想从服务器获取客户端IP地址。如果我使用这行代码,我会成功获得客户端IP:

udpServerSocket.ReceiveFrom(buffer, ref ep);

如果我改用下一行,则客户端IP会显示0.0.0.0

udpServerSocket.BeginReceiveFrom( buffer, 0, 1024, 
                                  SocketFlags.None, ref ep, 
                                  new AsyncCallback(ReceiveData), 
                                  udpServerSocket);

void ReceiveData(IAsyncResult iar)
{
    // Create temporary remote end Point
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint tempRemoteEP = (EndPoint)sender;

    // Get the Socket
    Socket remote = (Socket)iar.AsyncState;

    // Call EndReceiveFrom to get the received Data
    byte[] buf_ = new byte[255];
    int result = remote.Receive(buf_);

    int recv = remote.EndReceiveFrom(iar, ref tempRemoteEP);

    // Get the Data from the buffer to a string
    string stringData = Encoding.ASCII.GetString(buffer,0,recv);
    Console.WriteLine(stringData);

    // update Timestamp
    lastUpdate = DateTime.Now.ToUniversalTime();

    // Restart receiving
    if(!this.IsDisposed)
    {
       // udpServerSocket.ReceiveFrom(buffer, ref ep);
       udpServerSocket.BeginReceiveFrom(buffer, 0, 1024, 
                                        SocketFlags.None, ref ep, 
                                        new AsyncCallback(ReceiveData), 
                                        udpServerSocket);
        //remote.Connect(ep);
    }  
}

0 个答案:

没有答案