好吧,改变了一切,尝试问一个更具体的问题。
我有两个方法。doOnePing是我为使用sendOnePing而创建的,它是为帮助我更好地理解套接字而编写的。
我正在尝试理解我是否在doOnePing中正确地创建了套接字,我相信我是正确的,但我不确定我是否遗漏了一些特定的东西,或者是否可以做得更好。
谢谢
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
# Convert 16-bit integers from host to network byte order
myChecksum = htons(myChecksum) & 0xffff
else:
myChecksum = htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
# Both LISTS and TUPLES consist of a number of objects
# which can be referenced by their position number within the object.
def doOnePing(destAddr, timeout):
icmp = getprotobyname("icmp")
# SOCK_RAW For more details: http://sock-raw.org/papers/sock_raw
# Fill in start
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Fill in end
myID = os.getpid() & 0xFFFF # Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay发布于 2017-07-20 20:55:50
考虑使用scapy来代替ping。通过运行以下命令,您可以很容易地获得scapy:
pip install scapy使用它,您将能够更容易地ping
https://stackoverflow.com/questions/29552258
复制相似问题