python奇数组播套接字异常

时间:2011-12-25 16:19:10

标签: python sockets multicast

我有一些示例python代码,我从另一个堆栈溢出答案(不记得在哪里),实现多播。以下代码应设置用于接收多播数据包的套接字对象。 我将它封装在类似的类中:

class Multisock:

def __init__(self, MCAST_GRP, MCAST_PORT, packsize):
    import socket
    import struct

    self.MCAST_GRP = MCAST_GRP
    self.MCAST_PORT = MCAST_PORT

    self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.sock.bind(('', MCAST_PORT))
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

    self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

def __init__(self, MCAST_GRP, MCAST_PORT, packsize): import socket import struct self.MCAST_GRP = MCAST_GRP self.MCAST_PORT = MCAST_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', MCAST_PORT)) mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

然而,这给了我这个错误:

Traceback (most recent call last):
  File "./Audiorecv.py", line 41, in <module>
    sock = MulticastNetworking.Multisock('244.1.1.1', 5007, chunk)
  File "/home/wheybags/Multicast-Voice-Chat/MulticastNetworking.py", line 30, in __init__
    self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument

这真的令人困惑,因为如果我只是将MCAST_GRP静态设置为表示ip的字符串,它可以正常工作,但如果我尝试使用构造函数参数,则会出现上述错误。

1 个答案:

答案 0 :(得分:2)

您正在使用的多播地址244.1.1.1无效。组播地址范围为224.0.0.0到239.255.255.255。我用224.1.1.1运行你的代码,这是一个有效的地址,它运行得很好。