Created
April 8, 2011 10:11
-
-
Save kennydude/909592 to your computer and use it in GitHub Desktop.
Simple UDP messaging tool in python to send cross-network messages to all other users. (Useful for people in multiple rooms at home!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# UDP messaging | |
try: | |
import tkMessageBox | |
def displayMessage(message): | |
tkMessageBox.showinfo("Message", message) | |
except ImportError: | |
pass | |
def geti(array, item): | |
try: | |
return array[item] | |
except Exception: | |
return "" | |
import sys, socket, struct, getpass | |
UDP_IP="239.192.1.100" | |
UDP_PORT=9898 | |
if sys.argv[0] == "udp-messaging.py": | |
sys.argv.pop(0) | |
arg = geti(sys.argv, 0) | |
message = geti(sys.argv, 1) | |
sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) | |
if arg == "server": | |
intf = socket.gethostbyname(socket.gethostname()) | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 20) | |
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1) | |
sock.bind( ('', UDP_PORT ) ) | |
intf = socket.gethostbyname(socket.gethostname()) | |
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(intf)) | |
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(UDP_IP) + socket.inet_aton(intf)) | |
while True: | |
data, addr = sock.recvfrom( 1024 ) | |
parts = data.split("|") | |
displayMessage("Message from " + parts[0] + ":\n" + parts[1]) | |
elif arg == "send": | |
message = getpass.getuser() + '|' + message | |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) | |
sock.sendto( message, (UDP_IP, UDP_PORT) ) | |
else: | |
print "Add server or send as commands" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment