接收Multicast数据报错
-
想使用组播的方式实现设备自动发现,在Python上经测试没有问题,可以正常接收,代码如下:
import socket import struct import sys multicast_group = '224.0.0.6' server_address = ('', 23333) # Create the socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind to the server address sock.bind(server_address) # Tell the operating system to add the socket to the multicast group # on all interfaces. group = socket.inet_aton(multicast_group) mreq = struct.pack('4sL', group, socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Receive/respond loop while True: print >>sys.stderr, '\nwaiting to receive message' data, address = sock.recvfrom(1024) print >>sys.stderr, 'received %s bytes from %s' % (len(data), address) print >>sys.stderr, data print >>sys.stderr, 'sending acknowledgement to', address sock.sendto('ack', address)
将代码改为MircoPython后,发现以下属性未定义
socket.INADDR_ANY socket.IPPROTO_IP socket.IP_ADD_MEMBERSHIP
就自己找到了Python中定义的对应值填入MircoPython中,代码如下:
sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) sock.bind(usocket.getaddrinfo('0.0.0.0', 23333)[0][-1]) group = inet_aton('224.0.0.6') mreq = ustruct.pack('4sL', group, 0) sock.setsockopt(0, 12, mreq) while True: print('waiting to receive message') data, address = sock.recvfrom(1024) print('received %s bytes from %s' % (len(data), address))
然后在OpenMV中运行就报如下错误:
Traceback (most recent call last): File "<stdin>", line 39, in <module> TypeError: object with buffer protocol required
请问这个是什么情况?是因为MircoPython不支持Multicast吗?
-
忘记说了MircoPython中socket.inet_aton()方法也没有,但是自己实现了一个,方法代码如下:
def inet_aton(ipv4): ips = ipv4.split('.') return int(ips[0]) * 2 ** 24 + int(ips[1]) * 2 ** 16 + int(ips[2]) * 2 ** 8 + int(ips[3])
-