用于Python3中本地LAN上的广播消息的UPD客户端和服务器

时间:2017-03-26 17:09:26

标签: python-3.x sockets udp broadcast

以下是Foundations of Python Network Programming

采用的UDP广播代码
#!/usr/bin/env python3 
# UDP client and server for broadcast messages on a local LAN

import argparse, socket

BUFSIZE = 65535

def server(interface, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((interface, port))
    print('Listening for datagrams at {}'.format(sock.getsockname()))
    while True:
        data, address = sock.recvfrom(BUFSIZE)
        text = data.decode('ascii')
        print('The client at {} says: {!r}'.format(address, text))

def client(network, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    text = 'Broadcast datagram!'
    sock.sendto(text.encode('ascii'), (network, port))

if __name__ == '__main__':
    choices = {'client': client, 'server': server}
    parser = argparse.ArgumentParser(description='Send, receive UDP broadcast')
    parser.add_argument('role', choices=choices, help='which role to take')
    parser.add_argument('host', help='interface the server listens at network the client sends to')
    parser.add_argument('-p', metavar='port', type=int, default=1060, help='UDP port (default 1060)')
    args = parser.parse_args()
    function = choices[args.role]
    function(args.host, args.p)

我通过运行ifconfig |grep inet来确定我的笔记本电脑的广播IP 192.168.0.255

inet 127.0.0.1 netmask 0xff000000 
inet6 ::1 prefixlen 128 
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 
inet6 fe80::3f:e4b3:b7fb:5de8%en0 prefixlen 64 secured scopeid 0x4 
inet 192.168.0.27 netmask 0xffffff00 broadcast 192.168.0.255
inet6 fe80::7409:5aff:fe4b:ccf6%awdl0 prefixlen 64 scopeid 0x8 
inet6 fe80::5f53:baa3:9e02:e706%utun0 prefixlen 64 scopeid 0xa

然后我在两个不同的终端创建了两个服务器,一个是python3 udp_broadcast.py server localhost,另一个是python3 udp_broadcast.py server 192.168.0.27

在此之后,我尝试在第三个终端中运行python3 udp_broadcast.py client 192.168.0.255,但前面两个服务器都没有收到任何消息。(为什么不呢?

但是,如果我运行python3 udp_broadcast.py client localhostpython3 udp_broadcast.py client 192.168.0.27,则其中一个相应的服务器会收到一条消息。

最后,我创建了另一台服务器,即python3 udp_broadcast.py server 192.168.0.255,如果正在运行python3 udp_broadcast.py client 192.168.0.255,此服务器将收到消息,如下所示:

The client at ('192.168.0.27', 56303) says: 'Broadcast datagram!'

请注意,服务器发出客户端的IP地址是192.168.0.27而不是192.168.0.255。(为什么会改变?

似乎广播根本不起作用。非常感谢,如果有人能说明这一点!

0 个答案:

没有答案