你如何在Python中UDP多播?

时间:2009-03-02 20:24:10

标签: python multicast

如何在Python中发送和接收UDP多播?有标准库吗?

11 个答案:

答案 0 :(得分:86)

这对我有用:

接收

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
IS_ALL_GROUPS = True

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
    # on this port, receives ALL multicast groups
    sock.bind(('', MCAST_PORT))
else:
    # on this port, listen ONLY to MCAST_GRP
    sock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

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

while True:
  print sock.recv(10240)

发送

import socket

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
# regarding socket.IP_MULTICAST_TTL
# ---------------------------------
# for all packets sent, after two hops on the network the packet will not 
# be re-sent/broadcast (see https://www.tldp.org/HOWTO/Multicast-HOWTO-6.html)
MULTICAST_TTL = 2

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

它基于http://wiki.python.org/moin/UdpCommunication中不起作用的示例。

我的系统是...... Linux 2.6.31-15-generic#50-Ubuntu SMP Tue 11月10日14:54:29 UTC 2009 i686 GNU / Linux Python 2.6.4

答案 1 :(得分:17)

广播到多播组的多播发送方:

#!/usr/bin/env python

import socket
import struct

def main():
  MCAST_GRP = '224.1.1.1'
  MCAST_PORT = 5007
  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
  sock.sendto('Hello World!', (MCAST_GRP, MCAST_PORT))

if __name__ == '__main__':
  main()

从多播组读取并将十六进制数据打印到控制台的多播接收器:

#!/usr/bin/env python

import socket
import binascii

def main():
  MCAST_GRP = '224.1.1.1' 
  MCAST_PORT = 5007
  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  try:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  except AttributeError:
    pass
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) 
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)

  sock.bind((MCAST_GRP, MCAST_PORT))
  host = socket.gethostbyname(socket.gethostname())
  sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
  sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, 
                   socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))

  while 1:
    try:
      data, addr = sock.recvfrom(1024)
    except socket.error, e:
      print 'Expection'
      hexdata = binascii.hexlify(data)
      print 'Data = %s' % hexdata

if __name__ == '__main__':
  main()

答案 2 :(得分:11)

更好用:

sock.bind((MCAST_GRP, MCAST_PORT))

而不是:

sock.bind(('', MCAST_PORT))

因为,如果您想在同一端口上侦听多个多播组,您将获得所有侦听器上的所有消息。

答案 3 :(得分:4)

为了加入组播组,Python使用本机OS套接字接口。由于Python环境的可移植性和稳定性,许多套接字选项直接转发到本机套接字setsockopt调用。多播操作模式(例如加入和删除组成员资格)只能由setsockopt完成。

接收组播IP数据包的基本程序如下:

from socket import *

multicast_port  = 55555
multicast_group = "224.1.1.1"
interface_ip    = "10.11.1.43"

s = socket(AF_INET, SOCK_DGRAM )
s.bind(("", multicast_port ))
mreq = inet_aton(multicast_group) + inet_aton(interface_ip)
s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, str(mreq))

while 1:
    print s.recv(1500)

首先,它创建套接字,绑定它并通过发出setsockopt触发触发多播组加入。在最后它永远收到数据包。

发送多播IP帧是直截了当的。如果您的系统中有单个NIC,则发送此类数据包与通常的UDP帧发送没有区别。您需要注意的只是在sendto()方法中设置正确的目标IP地址。

我注意到很多关于互联网的例子实际上是偶然的。即使是官方的python文档。所有这些问题都错误地使用了struct.pack。请注意,典型示例使用4sl作为格式,并且它与实际的OS套接字接口结构不一致。

我将尝试描述在执行setockopt调用python套接字对象时发生在幕后的内容。

Python将setsockopt方法调用转发给本机C套接字接口。 Linux套接字文档(参见man 7 ip)为IP_ADD_MEMBERSHIP选项引入了两种形式的ip_mreqn结构。最短的形式是8个字节长,更长的是12个字节长。上面的示例生成8字节setsockopt调用,其中字节的第一个定义multicast_group和第二个interface_ip

答案 4 :(得分:2)

看看py-multicast。网络模块可以检查接口是否支持多播(至少在Linux上)。

import multicast
from multicast import network

receiver = multicast.MulticastUDPReceiver ("eth0", "238.0.0.1", 1234 )
data = receiver.read()
receiver.close()

config = network.ifconfig()
print config['eth0'].addresses
# ['10.0.0.1']
print config['eth0'].multicast
#True - eth0 supports multicast
print config['eth0'].up
#True - eth0 is up

未看到IGMP的问题可能是由不支持多播的接口引起的?

答案 5 :(得分:2)

答案 6 :(得分:2)

是另一个答案,以解释其他答案的代码中的一些细微之处:

  • socket.INADDR_ANY-并不会真正绑定到所有接口,而只是选择本地接口之一
  • 加入多播组不同于将套接字绑定到本地接口地址

有关多播如何工作的更多信息,请参见What does it mean to bind a multicast (UDP) socket?

多播接收器:

import socket
import struct
import argparse


def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.inet_aton(group),
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

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

    while True:
        print(sock.recv(10240))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
    parser.add_argument(
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
    parser.add_argument(
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to 0.0.0.0 '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

示例用法:(在两个控制台中运行以下命令,然后选择自己的--iface(必须与接收多播数据的接口相同)

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.1' '224.1.1.2' '224.1.1.3' --bind-group '224.1.1.2'

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.4'

多播发件人:

import socket
import argparse


def run(group, port):
    MULTICAST_TTL = 20
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from multicast_send.py: ' +
                f'group: {group}, port: {port}'.encode(), (group, port))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='224.1.1.1')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

样本用法:#假设接收者绑定到下面的多播组地址,并且某些程序请求加入该组。为了简化这种情况,假设接收方和发送方在同一子网中

python3 multicast_send.py --mcast-group '224.1.1.2'

python3 multicast_send.py --mcast-group '224.1.1.4'

答案 7 :(得分:0)

要使客户端代码(来自tolomea)在Solaris上运行,您需要将IP_MULTICAST_TTL套接字选项的ttl值作为unsigned char传递。否则你会收到错误。 这在Solaris 10和11上适用于我:

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
ttl = struct.pack('B', 2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

答案 8 :(得分:0)

由于一个晦涩的原因,此示例对我不起作用。

不是很模糊,它是简单的路由。

在OpenBSD上

route add -inet 224.0.0.0/4 224.0.0.1

您可以在Linux上为开发者设置路由

route add -net 224.0.0.0 netmask 240.0.0.0 dev wlp2s0

将所有多播流量强制到Linux上的一个接口

   ifconfig wlp2s0 allmulti

tcpdump非常简单

tcpdump -n multicast

在您的代码中,您拥有:

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"

为什么 10240

多播数据包的大小应为 1316字节

答案 9 :(得分:-1)

托洛梅的回答对我有用。我也将它入侵socketserver.UDPServer

class ThreadedMulticastServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
    def __init__(self, *args):
        super().__init__(*args)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((MCAST_GRP, MCAST_PORT))
        mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

答案 10 :(得分:-4)

除IP地址外,组播流量与常规UDP没有区别。看看标准socket library。您可能能够找到基于套接字构建的内容并且更易于使用。