如何在C#中确定组播数据包的源IP?

时间:2010-02-18 20:45:31

标签: c# multicast

我需要确定向我发送多播数据包的机器的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?

1 个答案:

答案 0 :(得分:3)

不是你在LocalEndPoint变量中的答案,它是数据包源的终点,即另一端的dude。请注意,我可能会将此变量重命名为“remoteEP”,并将其初始化为非特定的变量以避免混淆。