Reputation: 41
I am trying to send "broadcast" message from server to many clients.
Who must call bind function server or client?
Upvotes: 0
Views: 286
Reputation: 8033
The short answer is: the clients have to issue bind(2)
.
Sample code in Python:
Console 1
>>> from socket import *
>>> s = socket(AF_INET, SOCK_DGRAM)
>>> s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
>>> s.bind(("0.0.0.0", 33440))
>>> s.recv(10000)
Console 2
>>> from socket import *
>>> s = socket(AF_INET, SOCK_DGRAM)
>>> s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
>>> s.bind(("0.0.0.0", 33440))
>>> s.recv(10000)
Console 3
>>> from socket import *
>>> s = socket(AF_INET, SOCK_DGRAM)
>>> s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
>>> s.sendto("Hello world", ("127.255.255.255", 33440))
11
Then you will see 'Hello world'
on Console 1 and 2.
After you issue s.recv(10000)
on both of Console1 and 2, you will get something like this:
$ LANG=C netstat -nu4ap | grep python
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
udp 0 0 0.0.0.0:33440 0.0.0.0:* 31939/python
udp 0 0 0.0.0.0:33440 0.0.0.0:* 31447/python
$ uname -a
Linux kaidev01 3.2.0-57-generic #87-Ubuntu SMP Tue Nov 12 21:35:10 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
Upvotes: 1