How do I determine the source IP of a multicast packet in C#?

耗尽温柔 提交于 2019-12-18 04:52:55

问题


I need to determine the IP of a machine that has sent me a multicast packet, so that I can respond to it via unicast.

I'm using the following csharp (.Net 3.5) code to receive the packets over a multicast connection (code has been edited for brevity, with error checking and irrelevant options removed):

IPEndPoint LocalHostIPEnd = new IPEndPoint(IPAddress.Any, 8623);
Socket UDPSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); 
UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1);

UDPSocket.Bind(LocalHostIPEnd);

//Join the multicast group
UDPSocket.SetSocketOption(
     SocketOptionLevel.IP,
     SocketOptionName.AddMembership,
     new MulticastOption(IPAddress.Parse("225.2.2.6")));

IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any ,Target_Port); 
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint; 

// Create the state object. 
StateObject state = new StateObject();
state.buffer.Initialize();
state.workSocket = UDPSocket;
state.id = "state0";
//Set up my callback
UDPSocket.BeginReceiveMessageFrom(
    state.buffer, 
    0,
    StateObject.BufferSize, 
    0,
    ref LocalEndPoint, 
    new AsyncCallback(ReceiveCallback), 
    state);

And here's the callback, where I'm trying to get the source IP:

private void ReceiveCallback( IAsyncResult ar ) 
{
    IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any, Target_Port);
    EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;

    // Read data from the remote device. 
    // The following code attempts to determine the IP of the sender,
    // but instead gets the IP of the multicast group.
    SocketFlags sFlags = new SocketFlags();
    IPPacketInformation ipInf = new IPPacketInformation();

    int bytesRead = client.EndReceiveMessageFrom(ar, ref sFlags,
        ref LocalEndPoint, out ipInf);

    log.Warn("Got address: " + ipInf.Address.ToString());
}

I know the correct source IP is in the IP header, since I can clearly see it there when I sniff the packet in wireshark. However, instead of printing out the IP of the sending system (192.168.3.4), the above code prints out the IP of the multicast group that I am subscribed to (225.2.2.6). Is there a way to get the source IP instead?


回答1:


Isn't your answer in the LocalEndPoint variable, which is the EndPoint of the packet's source, i.e., the dude on the other end. Note that I would probably rename this variable something like "remoteEP", and initialize it to something non-specific to avoid confusion.



来源:https://stackoverflow.com/questions/2292063/how-do-i-determine-the-source-ip-of-a-multicast-packet-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!