Skip to content

Instantly share code, notes, and snippets.

Created September 9, 2014 12:46
Show Gist options
  • Save anonymous/f7c4399afd42c4f36fea to your computer and use it in GitHub Desktop.
Save anonymous/f7c4399afd42c4f36fea to your computer and use it in GitHub Desktop.
Python 网络编程基础中的那个广播程序
#!/usr/bin/env python
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
MAX = 65535
PORT = 1060
if 2 <= len(sys.argv) <= 3 and sys.argv[1] == 'server':
s.bind(('', PORT))
print('Listening for broadcasts at', s.getsockname())
while True:
data, address = s.recvfrom(MAX)
print('The client at {0} says: {1}'.format(address, data.decode()))
elif len(sys.argv) == 3 and sys.argv[1] == 'client':
network = sys.argv[2]
s.sendto('Broadcast message!'.encode(), (network, PORT))
else:
print('usage: udp_broadcast.py server', sys.stderr)
print('or: udp_broadcast.py client <host>', sys.stderr)
sys.exit(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment