我需要确定向我发送多播数据包的机器的 IP,以便我可以通过单播对其进行响应。
我正在使用以下 csharp (.Net 3.5) 代码通过多播连接接收数据包(为简洁起见,对代码进行了编辑,删除了错误检查和不相关的选项):
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);
这是回调,我正在尝试获取源 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());
}
我知道正确的源 IP 在 IP 标头中,因为当我在 Wireshark 中嗅探数据包时,我可以清楚地看到它。但是,上面的代码并没有打印出发送系统的 IP (192.168.3.4),而是打印出我订阅的多播组的 IP (225.2.2.6)。有没有办法获取源IP?