C# UDP Socket: Get receiver address

前端 未结 5 1629
萌比男神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:38

    I just had the same problem. I don't see a way, using ReceiveFrom or its async variants, to retrieve the destination address of a received packet.

    However...If you use ReceiveMessageFrom or its variants, you'll get an IPPacketInformation (by reference for ReceiveMessageFrom and EndReceiveMessageFrom, or as a property of the SocketAsyncEventArgs passed to your callback in ReceiveMessageFromAsync). That object will contain the IP address and interface number where the packet was received.

    (Note, this code has not been tested, as i used ReceiveMessageFromAsync rather than the fakey-fake Begin/End calls.)

    private void ReceiveCallback(IAsyncResult iar)
    {
        IPPacketInformation packetInfo;
        EndPoint remoteEnd = new IPEndPoint(IPAddress.Any, 0);
        SocketFlags flags = SocketFlags.None;
        Socket sock = (Socket) iar.AsyncState;
    
        int received = sock.EndReceiveMessageFrom(iar, ref flags, ref remoteEnd, out packetInfo);
        Console.WriteLine(
            "{0} bytes received from {1} to {2}",
            received,
            remoteEnd,
            packetInfo.Address
        );
    }
    

    Note, you should apparently call SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true) as part of setting up the socket, before you Bind it. The ...ReceiveMessageFrom... methods will set it for you, but you'll probably only see valid info on any packets Windows saw after the option was set. (In practice, this isn't much of an issue -- but when/if it ever happened, the reason would be a mystery. Better to prevent it altogether.)

提交回复
热议问题