squinnondation/for_testing_multicast/peer.py

32 lines
1.0 KiB
Python

from typing import Any, Tuple, Generator
from ipaddress import IPv6Address
import re
import socket
import time
import struct
# Initialise socket for IPv6 datagrams
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# Allows address to be reused
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Binds to all interfaces on the given port
sock.bind(('', 1212))
# Allow messages from this socket to loop back for development
#sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, True)
# Construct message for joining multicast group
#mreq = struct.pack("16s15s".encode('utf-8'), socket.inet_pton(socket.AF_INET6, "ff02::4242:4242"), (chr(0) * 16).encode('utf-8'))
mreq = struct.pack("16s15s", socket.inet_pton(socket.AF_INET6, "ff02::4242:4242"), bytes(socket.INADDR_ANY))
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
data, addr = sock.recvfrom(1024)
print(data)
print(addr[0], addr[1])
time.sleep(3)
sock.sendto("hello world".encode('utf-8'), ("addr[0]", int(addr[1])))