SUMMARY
This article shows you how to use the
Socket.SetSocketOption method with the socket option name parameter as
MulticastInterface.
back to the top
The SetSocketOption Method
The
SetSocketOption method of the Microsoft .NET Framework
Socket class takes three parameters:
- SocketOptionLevel
- SocketOptionName
- optionValue
The
SocketOptionLevel defines option levels for the
SetSocketOption and the
GetSocketOption methods. The
SocketOptionName defines different option names for the socket class. The
optionValue parameter takes in the value for the particular option name.
When you use
MulticastInterface as the value for the
SocketOptionName enumeration, the
optionValue expects an Index value of the particular Network Adapter or Interface. Note that there is currently no API in the .NET Framework to determine the index of a particular adapter. Therefore, the user must input the index value.
The following sample code shows you how to use
SetSocketOption with the
MulticastInterface socket option name. Type or paste the following code in the
Main function of a new Microsoft Visual C# .NET console application:
int defaultPort = 5050;
string localName = Dns.GetHostName();
IPHostEntry hostEntry = new IPHostEntry();
hostEntry = Dns.GetHostByName(localName);
IPAddress localAddress = hostEntry.AddressList[0];
Socket mcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Bind the socket to default IP address and port.
mcastSocket.Bind(new IPEndPoint(localAddress,defaultPort));
Console.Write("\nSelect Adapter for outgoing Multicast packets (Adapter Index) : ");
int index = int.Parse(Console.ReadLine());
int optionValue = (int)IPAddress.HostToNetworkOrder(index);
Console.Write("\nMulticast Address - To add membership : ");
IPAddress mcastAddress = IPAddress.Parse(Console.ReadLine());
Console.Write("\nPort number - Where Multicast members are listening : ");
int mcastPort = int.Parse(Console.ReadLine());
MulticastOption mcastOpt = new MulticastOption(mcastAddress,localAddress);
// Add membership to the group.
mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOpt);
// Set the required interface for outgoing multicast packets.
mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, optionValue);
// Send multicast packets.
string data = "This is a multicast packet";
mcastSocket.SendTo(ASCIIEncoding.ASCII.GetBytes(data), new IPEndPoint(mcastAddress,mcastPort));
back to the top