Thursday, February 18, 2010

Programmer - How do I determeine the source IP of a multicast packet in C#?

Programmer Question

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?

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails