import struct
import time
import socket
import binascii
def main():
# 组播地址及端口号
group_ip = '239.2.2.2'
group_port = 12346
# 创建套接字
group_udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# 获取本地IP地址
local_ip = socket.gethostbyname(socket.gethostname())
# 绑定端口
group_udp_sock.bind((local_ip, group_port))
# 添加到组播
mreq = struct.pack('4sl', socket.inet_aton(group_ip), socket.INADDR_ANY)
group_udp_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
# 设置TTL值,组播在三层交换机通讯过程中每经过一次转发TTL值减1,等于0时数据则不在转发
# group_udp_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 5)
# 设置数据接收取缓存大小
group_udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8192)
while True:
try:
data, addr = group_udp_sock.recvfrom(1024)
data1 = binascii.hexlify(data)
print(
f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}, 接收地址:{addr} 接收消息:{data1}'
)
print(len(data))
except:
print('接收消息错误')
if __name__ == '__main__':
main()
在模拟中发送的数据十六进制:33 33 33 33 33 33 03 00
代码中接收显示:接收消息:3333333333330300
就是收显示时候如何字节中间也有空格