Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sender ip from multicast packet

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.

like image 215
Stuart Blackler Avatar asked Nov 26 '12 00:11

Stuart Blackler


1 Answers

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

like image 91
Gille Avatar answered Sep 27 '22 22:09

Gille