Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从多播数据包获取发送方ip_C#_Network Programming_Multicast - Fatal编程技术网

C# 从多播数据包获取发送方ip

C# 从多播数据包获取发送方ip,c#,network-programming,multicast,C#,Network Programming,Multicast,如何获取多播UDP数据包的发送方的IP?当前代码以同步/分块方式设置(见下面的注释)。代码如下: private void receive() { string mcastGroup = SetMcastGroup(); s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s.EnableBroadcast = true;

如何获取多播UDP数据包的发送方的IP?当前代码以同步/分块方式设置(见下面的注释)。代码如下:

    private void receive()
    {
        string mcastGroup = SetMcastGroup();
        s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        s.EnableBroadcast = true;
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5000);
        s.Bind(ipep);
        IPAddress ip = IPAddress.Parse(mcastGroup);
        s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));

        while (true)
        {
            try
            {
                byte[] b = new byte[4096];
                s.Receive(b);
                string str = Encoding.ASCII.GetString(b, 0, b.Length);
                //this.SetText(ipep.Address + ": " + str.Trim());
                this.SetText(senderIP() + ": " + str.Trim());
            }
            catch{}
        }
    }

注意:这个问题来自聊天,因此不是我的代码。我之所以问这个问题,是因为我理解这个问题。

因为您使用的是UDP,所以您没有与远程端点建立连接(与TCP不同,在TCP中,每个连接只有一个套接字)。因此,在接收数据报时,必须获取远程端点的地址。要执行此调用,请调用
receiveFrom
,而不是
receive()


请不要使用空的
catch{}
。它只是掩盖错误,使问题更难识别。如果您试图忽略某个特定的异常,请针对该特定类型(例如,
catch filenotfoundexception{}
)@JonathonReinhart您是否阅读了关于我说这不是我的代码错误的评论?我很抱歉没有看到。但是,我不会称之为“燃烧”,我会称之为“提出建设性的建议”。我认为您应该使用s.receiveFrom()而不是s.receive()