创建Python Pinger - 套接字

时间:2015-04-10 02:18:39

标签: python

好的,改变一切尝试并提出更具体的问题。

我有两种方法。 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

1 个答案:

答案 0 :(得分:0)

考虑使用scapy来ping。你可以通过运行来轻松获得scapy:

pip install scapy

使用此功能,您可以更轻松地ping通