当前位置: 首页 > 工具软件 > 文播 > 使用案例 >

Linux下组播报文的发送与接收

苏宜人
2023-12-01

一、组播报文的发送

作为组播信息的提供者向组播组发送报文

可以参考如下代码:

首先需要将组播ip加入路由表中:

sudo route add -net 239.127.15.11 netmask 255.255.255.255 dev eth1

参数说明:

239.127.15.11:为组播ip

eth1:为发送报文的网卡名称(通过ifconfig查看) 

import socket

DSTPORT = 11111     #报文的目的端口
SRCPORT = 22222     #报文的源端口
SRCADDR = '192.168.23.12'       #发送报文的网卡ip
MULTICAST = '239.127.15.11'    #组播组ip


class MultiCastSend:

    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.multicast_group = (MULTICAST, DSTPORT)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                               socket.inet_aton(MULTICAST) + socket.inet_aton(SRCADDR))

    def send_multicast_data(self, data: bytes):
        self.socket.sendto(data, self.multicast_group)

    def close(self):
        self.socket.close()


if __name__=="__main__":
    send_obj = MultiCastSend()
    content = b'\x01\x02\x03\x04'
    send_obj.send_multicast_data(content)
    send_obj.close()
    

二、组播报文的接收

Linux下通过socket接收组播报文时,同理需要将组播ip加入路由。

可以参考如下的代码:

import socket


class MultiCastRecv:


    def __init__(self,multicastip:str,port:int,timeout=5):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        multicast_group = multicastip
        address = ('', port)
        group = socket.inet_aton(multicast_group)
        mreq = struct.pack('4sL', group, socket.INADDR_ANY)
        test_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        test_socket.bind(address)
        test_socket.settimeout(timeout)
        self.data = None

    
    def recv_data(self):
         self.data,addr = self.socket.recvfrom(4096)


if __name__ == "__main__":
    recv_obj = MultiCastRecv('239.127.11.1',11111)
    recv_obj.recv_data()
    content = recv_obj.data
    print(f'Recv data is {content}')
        

 类似资料: