Skip to content

Instantly share code, notes, and snippets.

@ArcticLight
Created April 28, 2014 03:07
Show Gist options
  • Save ArcticLight/11360802 to your computer and use it in GitHub Desktop.
Save ArcticLight/11360802 to your computer and use it in GitHub Desktop.
Receiver and Sender py
# chat server using multicast
# python fork of the original ruby implementation
# http://tx.pignata.com/2012/11/multicast-in-ruby-building-a-peer-to-peer-chat-system.html
# receiver.py
# usage : $ python receiver.py # wait for messages to come in
import socket
import struct
multicast_addr = '224.0.0.1'
bind_addr = '0.0.0.0'
port = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
membership = socket.inet_aton(multicast_addr) + socket.inet_aton(bind_addr)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((bind_addr, port))
while True:
message, address = sock.recvfrom(255)
print message
# chat server using multicast
# python fork of the original ruby implementation
# http://tx.pignata.com/2012/11/multicast-in-ruby-building-a-peer-to-peer-chat-system.html
# send.py
# usage : $ python send.py message
import socket
import struct
import sys
message = sys.argv[1] if len(sys.argv) > 1 else 'message via multicast'
multicast_addr = '224.0.0.1'
port = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ttl = struct.pack('b', 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto(sys.argv[1], (multicast_addr, port))
sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment