Receive需要一下IPEndPoint 参数啊,它会返回IP地址的你是没发过帖子导致结贴率为0还是从来没结过?

解决方案 »

  1.   

    是啊,我是第一次来CSDN,朋友介绍的
      

  2.   


     IPHostEntry iphost = new IPHostEntry();
     iphost = Dns.GetHostEntry(Dns.GetHostName());
     IPEndPoint ipend = new IPEndPoint(iphost.AddressList[0], 11000);
     UdpClient= new UdpClient(ipend);  byte[] recvData = uc.Receive(ref ipend);
     string recvString = System.Text.Encoding.UTF8.GetString(recvData);我是这样写的,但接收到的只有发来的信息内容,没有对方的IP和端口号
      

  3.   

    个人认为二楼说得没错,MSDN 中的例子:
     //Creates an IPEndPoint to record the IP Address and port number of the sender. 
    // The IPEndPoint will allow you to read datagrams sent from any source.
     IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
     try{     // Blocks until a message returns on this socket from a remote host.
         Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); 
    ...Receive 调用完成后,RemoteIpEndPoint 里面就应该是实际发送方的相关信息了。ref 不是白 ref 的。
      

  4.   

    我还见过先 IPEndPoint remoteEP = null; 的,做一次 Receive,之后再 Send 的时候,就可以持续用 remoteEP 了。
    感觉这么写很自然。开始不知道谁发来消息,一旦收到谁的消息(报文)了,就回应对方。
      

  5.   

    我晕byte[] recvData = uc.Receive(ref ipend); 
    Receive返回已由远程主机发送的 UDP 数据。
    public byte[] Receive (
        ref IPEndPoint remoteEP
    )remoteEP就是你说的对方ip 和端口
    msdn的备注(虽然中文翻译的叫人难受,但是大概说明白了)
    备注 
    Receive 方法将阻止,直到数据报从远程主机到达为止。如果数据可用,则 Receive 方法将读取入队的第一个数据报,并将数据部分作为字节数组返回。此方法使用发送方的 IPAddress 和端口号来填充 remoteEP 参数。如果在 Connect 方法中指定了默认远程主机,则 Receive 方法将只接受来自该主机的数据报。其他所有数据报将被丢弃。如果收到 SocketException,请使用 SocketException.ErrorCode 获取特定的错误代码。获取该代码后,可以参考 MSDN 中的 Windows Sockets version 2 API(Windows 套接字第 2 版 API)错误代码文档以获取有关错误的详细说明。
      

  6.   

    byte[] data = udpClient.Receive(ref endPoint);
    接收完后参数endPoint会被设置成对方的地址,所以上一句执行完后:
    endPoint.Address就是对方ip
    endPoint.Port就是对方端口