How to determine the source IP address of a multicast packet in C #?

I need to determine the IP address of the machine that sent me the multicast packet so that I can respond to it through unicast.

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

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 is the callback where I am trying to get the original IP address:

 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 that the correct source IP address is in the IP header, since I can clearly see it there when I sniff a packet in wirehark. However, instead of printing the IP address of the sending system (192.168.3.4), the code above displays the IP address of the multicast group that I subscribed to (225.2.2.6). Is there any way to get the source IP address?

+7
c # multicast
source share
1 answer

Not your answer in the LocalEndPoint variable, which is the endpoint of the package source, i.e. the dude on the other end. Note that I would probably rename this variable as "remoteEP" and initialize it with something non-specific to avoid confusion.

+3
source share

All Articles