相关疑难解决方法(0)

C#UDP套接字:获取接收者地址

我有一个异步UDP服务器类,其中一个套接字绑定在IPAddress.Any上,我想知道收到的数据包被发送到哪个IP地址(...或接收到).看来我不能只使用Socket.LocalEndPoint属性,因为它总是返回0.0.0.0(这是有意义的,因为它绑定到那个......).

以下是我目前使用的代码的有趣部分:

private Socket udpSock;
private byte[] buffer;
public void Starter(){
    //Setup the socket and message buffer
    udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    udpSock.Bind(new IPEndPoint(IPAddress.Any, 12345));
    buffer = new byte[1024];

    //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);
}

private void DoReceiveFrom(IAsyncResult iar){
    //Get the received message.
    Socket recvSock = (Socket)iar.AsyncState;
    EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
    int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP);
    byte[] localMsg = new byte[msgLen]; …
Run Code Online (Sandbox Code Playgroud)

c# sockets udp asyncsocket

18
推荐指数
1
解决办法
2万
查看次数

标签 统计

asyncsocket ×1

c# ×1

sockets ×1

udp ×1