27742 total geeks with 3539 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 



User's box

Forgot password?
New account

[b][url=http ://www.montb lancspens.to p/]p<strong> <a href="http:/ /www.montbla ncspens.top/ ">pens</a></ strong> <br> <strong><a href="http:/ /www.montbla ncspens.top/ ">mont blanc pens</a></st rong> <br>
[b][url=http ://www.farma koplus.com/] swiss repli<strong ><a href="http:/ /www.farmako plus.com/">s wiss replica watches aaa+</a></st rong> <br> <strong><a href="http:/ /www.farmako plus.com/">s wiss replica watches</a>< /strong> <br >
[b][url=http ://www.isobe -sr.com/]swi ss replic<stron g><a href="http:/ /www.isobe-s r.com/">swis s replica watches aaa+</a></st rong> <br> <strong><a href="http:/ /www.isobe-s r.com/">swis s replica watches</a>< /strong> <br >
[b][url=http ://www.watch thegroup.com /]swiss repli<strong ><a href="http:/ /www.watchth egroup.com/" >swiss replica watches aaa+</a></st rong> <br> <strong><a href="http:/ /www.watchth egroup.com/" >swiss replica watches</a>< /strong> <br >
[b][url=http ://www.nikes hoesoutlet.c c/]footb<str ong><a href="http:/ /www.nikesho esoutlet.cc/ ">football boots</a></s trong> <br> <strong><a href="http:/ /www.nikesho esoutlet.cc/ ">nike shoes outlet</a></ strong> <br>

Donate and help us fund new challenges
Due Date: Nov 30
November Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00

News Feeds
The Register
Downloads for
Windows 10 November
big-bang build axed
by Microsoft
Who"s right on
crypto: An American
prosecutor or a
Lebanese coder?
ESXi"s been borking
VM backup and
there"s no fix yet
Video still causing
mobile data traffic
to shoot through
the roof
British duo
arrested for
malwarell> encryption
Paris, jihadis,
tech giants ...
What is David
banging on about
World"s most
complex cash
register malware
plunders millions
in US
Pen tester sounds
alert over "gaping"
flaws in Brit alarm
Dum dum dum -
another cloud bites
the dust (Adobe"s
photo cloud)
What America"s
drone owner
database could look
like in future
Gene Drive Turns
Mosquitoes Into
Malaria Fighters
Axel Springer Goes
After iOS 9 Ad
Blockers In New
Legal Battlle
Understanding the
Cuban Talks Trash
At Intel Extreme
Masters, Drops $30K
of F-Bombs For
Patreon Users
Threatened By
Ashley Madison
Fake Bomb Detector,
Blamed For Hundreds
of Deaths, Is Still
In Use
With $160 Billion
Merger, Pfizer
Moves To Ireland
and Dodges Taxes
Can Full-Time Tech
Workers Survive the
Gig Economy?
FAA To Drone
Owners: Get Ready
To Register To Fly
NASA Contracting
Development of New
Ion/Nuclear Engines
Article viewer

Implementing Multicast Sockets in C#

Written by:dimport
Published by:thinkt4nk
Published on:2003-06-21 07:19:46
Search OSI about Dot.Net.More articles by dimport.
 viewed 109846 times send this article printer friendly

Digg this!
    Rate this article :
Ever wanted to broadcast to everyone but still be able to use the net? How about being able to send data only to the nodes that really requested it?Interested? well this is where the next generation of broadcast comes in -> Multicast.

The Multicast method uses the same idea as broadcast - connectionless messaging, to many nodes - UDP transport of datagrams.The Multicast is a standard communication method and is supported in most network implementations (FDDI, Token Ring, Ethernet, etc.)

The Multicast Datagram
The only allowed address range for multicast groups is Class D - to the first address is for communicating with routers (, andall the NICs (Network Interface card) automatically joins this group.

The Multicast Workflow
One of the main ideas behind multicast is to reduce the load on hosts which are not interested in information, meaning that the packet coming from the network is discarded in a very early begining of the protocol stack, if possible, then on the interface card (NIC):Protocol Stack:UDPIPDevice DriverInterface Cardthis doesn't happen in broadcast, since there filtering occours only at the UDP layer.Another another advantage is the fact that routers relay multicast traffic to other routers so all the hosts in the network which Joined a specific group would recieve this data.This is where IGMP (Internet Group Managment Protocol) comes in:If the multicast is implemented on a single LAN, nothing is done with the IGMP reports, but if there are routers in the network, then they start mapping the nodes which belong togroup and start monitoring groups to make sure, there are still nodes which belong to any group.Every couple of minutes the router sends a query message to each group to see if there are still nodes in it, if there is a response from anyone in the group, then nothing is happened, and the router keeps transmitting multicast packets into the network.else, the router will throw the incoming multicast packets, since no nodes exists in the group to which the packet is directed.

The IGMP Message within an IP datagram:|----------------------|--------------||IP Header (20 bytes) | IGMP Message||----------------------|--------------|Format of the fields in IGMP message:|--------------|---------------|------------|---------------------------||4-bit | 4-bit | |||IGMP | IGMP | Unused | 16-bit checksum ||Version (1) | type (1-2) | |||-----------------------------------------------------------------------||32-bit group address (IP address class D) ||-----------------------------------------------------------------------|The IGMP version is 1.The value of type=1 is a query message sent by a multicast routetr.The value of type=2 is a respone sent by a host.The group address is a class D IP address:* In a query the address is set to 0* In the report, the address is set to the multicast group address being reportedOne of the best things about Multicast packets, is the fact the you can control the amount of hops a packet is doing between routers, so that multicast packets only stay in thesame subnet / network, this field is the TTL - Time to live.

Implementing The Multicast
//Socket creation, regular UDP socket
private Socket UDPSocket = new
private string Target_IP = "";
private int Target_Port = 31337;

//socket initialization
public MulticastSocket()
//nothing should go wrong in here
//recieve data from any source
IPEndPoint LocalHostIPEnd = new

//init Socket

//allow for loopback testing

//extremly important to bind the
Socket before joining multicast groups

//set multicast flags, sending flags - TimeToLive (TTL)
// 0 - LAN
// 1 - Single Router Hop
// 2 - Two Router Hops...

//join multicast group


//get in waiting mode for data -
always (this doesn't halt code execution)
catch (Exception e)
Console.WriteLine(ex.Message + "
" + ex.StackTrace);

//client send function
public void Send(string sendData)
byte[] bytesToSend = Encoding.ASCII.GetBytes(sendData);

//set the target IP
IPEndPoint RemoteIPEndPoint = new
EndPoint RemoteEndPoint = (EndPoint)RemoteIPEndPoint;

//do asynchronous send
UDPSocket.BeginSendTo(bytesToSend, 0,
bytesToSend.Length, SocketFlags.None,RemoteEndPoint,
new AsyncCallback(SendCallback), UDPSocket);


//executes the asynchronous send
private void SendCallback(IAsyncResult ar)
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = client.EndSendTo(ar);

catch (Exception e)


//initial receive function - called only once
private void Recieve()
IPEndPoint LocalIPEndPoint = new
IPEndPoint(IPAddress.Any ,Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;

// Create the state object.
StateObject state = new StateObject();
state.workSocket = UDPSocket;

// Begin receiving the data from the remote device.
UDPSocket.BeginReceiveFrom(state.buffer, 0,StateObject.BufferSize,
0,ref LocalEndPoint,
new AsyncCallback(ReceiveCallback), state);
catch (Exception e)


//executes the asynchronous receive - executed everytime data
is received on the port
private void ReceiveCallback( IAsyncResult ar )

IPEndPoint LocalIPEndPoint = new
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;

// Retrieve the state object and the client socket
// from the async state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceiveFrom(ar,ref LocalEndPoint);

//keep listening
state.buffer, 0, StateObject.BufferSize, 0,ref LocalEndPoint,
new AsyncCallback(ReceiveCallback), state);
catch (Exception e)

Using the New Socket
You can find the test project and all source codes here**********************Interesting Facts:1. A multicast packet is actually a UDP packet2. multicast address range is from to multicast can be implemented on a simple LAN with no routers, just TCP/IP4. multicast is much better than broadcast5. is a permanent address assisgned by the IANA, which means "all hosts on this subnet"6. is also a permanent address which means "all routers in a this subnet"7. is for NTP - Network Time Protocol8. is used by DVMRP (Distance Vector Multicast Routing Protocol) - used for multicast routing ;)9. Don't use the XP Firewall option protection on the NIC - this won't allow you to get broadcast / multicast packets from the network**********************Sources:TCP/IP Ilustrated, Volume 1 - W. Richard Stevens (2000)MSDN

This article was originally written by nashcontrol

Did you like this article? There are hundreds more.

2007-02-04 17:16:54
For multicast, also take a look at http://code.google.com/p/emcaster/. It is a free library that supports multiple transports (PGM and UDP) and regular expression based topics.
2007-03-27 17:02:23
Hi. The link to the source doesn't work.
Any chance it could be updated?
2007-04-10 14:43:28
the code does not work

BeginReceiveFrom throws an exception
2009-03-05 17:40:17
This is extremely unhelpful. Very vague code with errors. Not intuitive, no working example, no explanation for the unapparent logic used.

It's sad to see this as the first result on google.
2009-04-22 09:01:14
Well.. It seems the link to the source doesn't work. Any chance it could be updated? flash games
2009-05-20 16:41:53
very very very very very bad!!!!
2009-05-27 21:05:16
All works apart from the repeat recieve bit!
2009-10-18 18:00:47
bollicks... doesn;t work at all... what;s the point of submitting code if a simple copy paste isn't enough to make it work. if there are any assumptions, please mention them and don't expect the reader to figure them out. they want solutions. that's why they came here in the first place.
2009-10-18 20:47:33
No it isn't, I think people typically come here to learn, rather than just copy and paste chunks of code without understanding them...
2009-11-25 19:31:23
It is a dangerous business to copy and paste code without understanding it.
2010-02-27 20:12:42
Hey you whining douche bags. Stop complaining and appreciate the walk through from the author. I haven't run his code directly but I've used all the pieces to create my own little console app to send and receive multicast messages and it took me like 10 mins to do that. If you're expecting to be able to always find pre-chewed and pre-digested solutions on the web that will always work for everyone in every situation, then you're dreaming and you should go back to school and learn more about programming and software engineering.
2010-03-22 14:37:44
This doesnt work, StateObject is nowhere to be found!!! YOU SUCK ASS!!!
2010-12-05 15:53:51
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
2011-05-14 06:43:08
appriciated nice post....it worked for me, atleast got the idea from the author, thanks mate.
2011-06-16 07:31:03
That is certainly a number of peak performance goods. Couldn't know that will ideas may be this specific various. Appreciate your each of the eagerness to make available this sort of information below. Right this moment, the relationship is that one could merely obtain insurance plan via the driver that's signed up absolutely need point out.
obat asam urat
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:

Blogs: (People who have posted blogs on this subject..)
ASP.NET RadioButton GroupName when inside a Repeater on Sun 10th Jun 8am
I was thankful on finding this nugget of code, which makes the groupname work out when slamming in radiobuttons in an asp.net repeater. http://www.codeguru.com/csharp/csharp/cs _controls/custom/article.php/c12371/

Your Ad Here
Copyright Open Source Institute, 2006