在广播消息中绑定功能

时间:2014-01-25 13:27:47

标签: linux sockets udp broadcast

我正在尝试从服务器向许多客户端发送“广播”消息。

谁必须调用绑定功能服务器或客户端?

1 个答案:

答案 0 :(得分:1)

简短的回答是:客户必须发出bind(2)

Python中的示例代码:

控制台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)

控制台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)

控制台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

然后您将在控制台1和2上看到'Hello world'

更新

在Console1和2上发布s.recv(10000)后,您将得到以下内容:

$ 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