【发布时间】:2019-07-30 10:12:49
【问题描述】:
我偶然发现了 PyMOTW3 (https://pymotw.com/3/socket/multicast.html) 书中的一些代码,我不明白为什么生存时间(ttl) 参数被打包为 struct.pack('b',1).
我尝试搜索手册以查看是否应该打包参数,但它指出它可以是整数。我尝试输入一个普通整数,它似乎工作正常。它给出了与下面的代码相同的输出。那么它被这样包装有什么具体原因吗? 我知道将它打包为 1 是不必要的,因为 默认值为 1,但如果我需要使用其他数字怎么办。我需要打包吗?
我已经包含了下面书中的代码。
import socket
import struct
import sys
message = b'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block
# indefinitely when trying to receive data.
sock.settimeout(0.2)
# Set the time-to-live for messages to 1 so they do not
# go past the local network segment.
ttl = struct.pack('b', 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
print(s.getsockopt(socket.IPPROTO_IP,socket.IP_MULTICAST_TTL))
try:
# Send data to the multicast group
print('sending {!r}'.format(message))
sent = sock.sendto(message, multicast_group)
# Look for responses from all recipients
while True:
print('waiting to receive')
try:
data, server = sock.recvfrom(16)
except socket.timeout:
print('timed out, no more responses')
break
else:
print('received {!r} from {}'.format(
data, server))
finally:
print('closing socket')
sock.close()
无论我打包还是使用普通整数,这都是我得到的输出。
1
发送非常重要的消息
超时!
关闭套接字
【问题讨论】:
标签: python python-3.x sockets ttl multicastsocket