Zenet
Zenet

Reputation: 7411

How to broadcast a message in a network?

I'm working on a client-server application written in C. I want to broadcast a message to all the machines available on the local network.

How can I do that using the usual socket system calls in C?

Upvotes: 13

Views: 37590

Answers (4)

stefanB
stefanB

Reputation: 79810

Have a look at UDP sockets.

I recomend Beej's Guide to Network Programming. Have a look at 6.3 Datagram Sockets

Upvotes: 3

Adrien Plisson
Adrien Plisson

Reputation: 23303

you have to use UDP to send a broadcast message over a network. when creating your socket using the socket() function, specify AF_INET for the family parameter and SOCK_DGRAM for the type parameter. on some systems, you have to enable the sending of broadcast packet by setting the SO_BROADCAST socket option to 1, using setsockopt().

then use the sendto() function call to send a datagram, and use 255.255.255.255 as the destination address. (for datagram sockets, you don't need to call connect(), since there is no 'connection').

in standard implementations, this address broadcasts to all computer in the local network, this means that the packet will not cross gateway boundaries and will not be received by computers using a network mask diferent from the network mask of the sending computer.

Upvotes: 9

Enrico Carlesso
Enrico Carlesso

Reputation: 6934

Just send the message to the broadcast address of your subnet, which for 192.168.0.0/24 is 192.168.0.255, or just broadcast to 255.255.255.255.

Upvotes: 10

RC.
RC.

Reputation: 28207

You can use the special address of 255.255.255.255 to send a broadcast message to every computer on the local network.

For more info see section IP Network Broadcasting.

Upvotes: 1

Related Questions