Get sender IP address from multicast packet

How do you get the sender IP address of a UDP multicast packet? The current code is set 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 arises from chat, as this is not my code. I only ask because I understand the problem.

+6
source share
1 answer

Since you are using UDP, you are not establishing a connection with the remote endpoint (unlike TCP, where you will have one socket per connection). Therefore, when receiving a datagram, you must get the address of the remote endpoint. To do this, call receiveFrom instead of receive()

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

+3
source

All Articles