Raspberry Pi Python - 使用Socket在本地网络上工作的多播UDP

时间:2018-01-24 16:38:52

标签: python sockets networking raspberry-pi multicast

我目前的设置是:

  1. 1 x computer
  2. 1 x GS308v2以太网HUB
  3. 7 x raspberry pi's
  4. pi的静态ip的范围从192.168.1.2到192.168.1.9。 dhcpcd.conf文件如下:

    enter image description here

    发件人的python脚本:

    #!/usr/bin/python
    
    import socket
    import struct
    import sys
    import IN
    import subprocess
    import fcntl
    
    MULTICAST_GROUP = '224.1.1.1'
    MULTICAST_PORT = 12345
    
    path = "-o /var/www/html/images-folder/pic.jpg"
    
    SCMD = chr(1)
    SEND = SCMD + path
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    dev = "eth0" + "\0"
    sock.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, dev)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
    sock.sendto(SEND, (MULTICAST_GROUP, MULTICAST_PORT))
    sock.close()
    

    接收者的python:

    #!/usr/bin/python
    
    import socket
    import struct
    import fcntl
    from subprocess import call
    import sys
    
    MULTICAST_GROUP = '224.1.1.1'
    MULTICAST_PORT = 12345
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', MULTICAST_PORT))
    req = struct.pack("4sl", socket.inet_aton(MULTICAST_GROUP), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
    
    while True:
       data = sock.recv(10240)
    

    这一切都适用于路由器上的动态IP。但是没有使用静态ip的HUB工作。接收器脚本给出以下错误:

    Traceback (most recent call last):
      File "/home/pi/dummyPi.py", line 17, in <module>
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
      File "/usr/lib/python2.7/socket.py", line 228, in meth
        return getattr(self._sock,name)(*args)
    socket.error: [Errno 19] No such device
    

    如何配置此集线器x pi网络以执行此多播?

1 个答案:

答案 0 :(得分:0)

解决方案结果是,如果不使用路由器,也必须为Linux设置多播路由。以下命令保存了我:

sudo ip route add 224.0.0.0/4 dev eth0

如果有人想解释为什么这有效或者这个命令对网络的作用是什么,我会很乐意学习。随意评论。