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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With