从多播数据包获取发件人IP [英] Get sender ip from multicast packet

查看:104
本文介绍了从多播数据包获取发件人IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取多播UDP数据包的发送者的IP?当前代码以同步/阻止方式设置(请参见下面的注释).这是代码:

How do you get the IP of the sender of a Multicast UDP packet? The current code is setup in a synchronous/blocking manner (see note below). Here is the code:

    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{}
        }
    }

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

Note: This question comes from chat, as such is not my code. I am only asking because I understand the problem.

推荐答案

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

Since you are using UDP you don't establish a connection with the remote endpoint (unlike TCP where you would have one socket per connection). Therefore you must get the address of the remote endpoint when you receive the datagram. To do this call receiveFrom instead of receive()

http://msdn.microsoft. com/en-us/library/system.net.sockets.socket.receivefrom.aspx

这篇关于从多播数据包获取发件人IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆