I am trying to insert an input in a UDP multicast program in python. The sender is working fine but the receiving side is not decoding well as i am expecting. If i input more than two characters it throws this error:
Traceback (most recent call last):
File "/home/felix/PycharmProjects/Multicast UDP programming/client1.py", line 27, in <module>
data, addr = sock.recv(1024)
ValueError: too many values to unpack (expected 2)
but when i insert the two characters as expected it throws this kind of error:
Traceback (most recent call last):
File "/home/felix/PycharmProjects/Multicast UDP programming/client1.py", line 33, in <module>
msg = data.decode()
AttributeError: 'int' object has no attribute 'decode'
The code is shown below. Please help me review it.
Sender.py
import socket
group = '224.1.1.1'
port = 15000
# for all packets sent, after two hops on the network the packet will not be re-sent/broadcast
ttl = 2
# Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# Make the socket non-blocking
sock.setblocking(True)
# Set the multicast TTL
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
# Get input from the user
input_msg = input("Enter your message: ")
# Sends the packet/message
sock.sendto(input_msg.encode(), (group, port))
sock.close()
Receiver.py
import socket
import struct
cast_grp = socket.gethostbyname('224.1.1.1')
cast_port = 15000
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the socket to the multicast group and port
sock.bind(('', cast_port))
# Joins the multicast group
mreq = struct.pack("4sl", socket.inet_aton(cast_grp), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
# Make the socket non-blocking
sock.setblocking(True)
# Disable loopback for the multicast group
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
while True:
# creates a datagram packet and sends over the socket
try:
data, addr = sock.recv(1024)
except socket.error:
# No data available to receive
continue
# Decode the received data
msg = data.decode()
# Print the received message
print(f"{addr}:{msg}")
break
# Close the socket
sock.close()
I was expecting the code to work well since there are no errors or warnings
The
recv
method is meant to be called on a connected socket, and as such only returns the data, not the address. You should be usingrecvfrom
instead which gives you both.Sender output:
Receiver output: