Question about SetSocketOption & MulticastOption
I create a group & send a message 1 line before the method Receive
wait for a message by creating a thread. This code works Perfectly. I just want to know why shouldn't I add this line in the Send
method too for joining the socket to the group before I try send something to the group.
server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, MulticastOption);
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class MAIN
{
private static MulticastOption CreateGroup()
{
return new MulticastOption(IPAddress.Parse("224.100.0.1"));
}
private static void Receive(MulticastOption MulticastOption)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
EndPoint ep = (EndPoint)iep;
sock.Bind(iep);
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, MulticastOption);
开发者_开发知识库//
byte[] data = new byte[1024];
new Thread(new ThreadStart(Send)).Start();
int recv = sock.ReceiveFrom(data, ref ep);
String stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
sock.Close();
}
private static void Send()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
server.SendTo(data, iep);
server.Close();
}
public static void Main(String[] args)
{
Receive(CreateGroup());
Console.ReadKey();
}
}
From this article:
The IP_ADD_MEMBERSHIP option allows you to join a multicast group specified by the host group address in the multicast address structure. You must join a group to receive multicast datagrams. You do not need to join a group to send multicast datagrams.
However, this will only work on the local subnet due to the default TTL value. See this article for a more explicit answer.
精彩评论