98

如何在 Python 中发送和接收 UDP 多播?是否有标准库可以这样做?

4

9 回答 9

112

这对我有用:

收到

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:
  # For Python 3, change next line to "print(sock.recv(10240))"
  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)

# For Python 3, change next line to 'sock.sendto(b"robot", ...' to avoid the
# "bytes-like object is required" msg (https://stackoverflow.com/a/42612820)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

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

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

于 2009-11-25T03:03:07.967 回答
20

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

#!/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()
于 2009-07-20T03:40:37.433 回答
14

更好的使用:

sock.bind((MCAST_GRP, MCAST_PORT))

代替:

sock.bind(('', MCAST_PORT))

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

于 2011-10-06T13:55:47.557 回答
7

为了加入多播组 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。请注意,典型示例使用4slas 格式,与实际 OS 套接字接口结构不一致。

我将尝试描述在执行对 python 套接字对象的 setsockopt 调用时引擎盖下发生的事情。

Python 将 setsockopt 方法调用转发到本机 C 套接字接口。Linux 套接字文档(请参阅参考资料man 7 ip)介绍ip_mreqn了 IP_ADD_MEMBERSHIP 选项的两种结构形式。最短的格式是 8 字节长,更长的是 12 字节长。上面的示例生成 8 字节setsockopt调用,其中前四个字节定义multicast_group,后四个字节定义interface_ip

于 2017-03-28T15:23:38.117 回答
3

只是另一个答案来解释其他答案的代码中的一些微妙点:

  • socket.INADDR_ANY- (已编辑)在 的上下文中IP_ADD_MEMBERSHIP,这并没有真正将套接字绑定到所有接口,而只是选择多播启动的默认接口(根据路由表)
  • 加入多播组与将套接字绑定到本地接口地址不同

请参阅绑定多播 (UDP) 套接字是什么意思?有关多播如何工作的更多信息

组播接收器:

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'

于 2018-10-13T09:16:07.767 回答
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 的问题是由不支持多播的接口引起的?

于 2010-09-23T18:16:13.477 回答
0

要使客户端代码(来自 tolomea)在 Solaris 上工作,您需要将IP_MULTICAST_TTL套接字选项的 ttl 值作为无符号字符传递。否则你会得到一个错误。这在 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))
于 2014-01-24T12:12:32.773 回答
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 字节

于 2020-12-03T12:03:04.190 回答
-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)
于 2013-08-08T15:10:04.640 回答