2012-11-19 69 views
4

對於我的計算機網絡類,我試圖用ICMP協議使用原始套接字來實現Traceroute。我需要構建一個數據包,然後使用Python結構類來解壓縮響應數據包。以下是構建數據包的代碼:struct:unpack需要長度爲16的字符串參數

header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1) 
data = struct.pack("d", time.time()) 
packet = header + data 

後來,我收到一個ICMP數據包,其格式與確認相同。下面是打包數據包的代碼:

request_code, request_type, checksum, packet_id, \ 
       sequence, timeSent, data = struct.unpack("bbHHhd", recvPacket) 

但是我收到以下錯誤:struct.error: unpack requires a string argument of length 16

我不理解,因爲當我檢查struct.calcsize()格式字符串,它返回16

這裏是我的全部程序,如果你想在你的機器上運行它

from socket import * 
import socket 
import os 
import sys 
import struct 
import time 
import select 
import binascii 

ICMP_ECHO_REQUEST = 8 
MAX_HOPS = 30 
TIMEOUT = 2.0 
TRIES = 2 

# The packet that we shall send to each router along the path is the ICMP echo 
# request packet, which is exactly what we had used in the ICMP ping exercise. 
# We shall use the same packet that we built in the Ping exercise 

def checksum(str): 
    csum = 0 
    countTo = (len(str)/2) * 2 
    count = 0 

    while count < countTo: 
     thisVal = ord(str[count+1]) * 256 + ord(str[count]) 
     csum = csum + thisVal 
     csum = csum & 0xffffffffL 
     count = count + 2 

    if countTo < len(str): 
     csum = csum + ord(str[len(str) - 1]) 
     csum = csum & 0xffffffffL 

    csum = (csum >> 16) + (csum & 0xffff) 
    csum = csum + (csum >> 16) 
    answer = ~csum 
    answer = answer & 0xffff 
    answer = answer >> 8 | (answer << 8 & 0xff00) 
    return answer 

def build_packet(): 
    # In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our 
    # packet to be sent was made, secondly the checksum was appended to the header and 
    # then finally the complete packet was sent to the destination. 

    # Make the header in a similar way to the ping exercise. 
    # Header is type (8), code (8), checksum (16), id (16), sequence (16) 
    myChecksum = 0 
    pid = os.getpid() & 0xFFFF 

    # Make a dummy header with a 0 checksum. 
    # struct -- Interpret strings as packed binary data 
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1) 
    #header = struct.pack("!HHHHH", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1) 
    data = struct.pack("d", time.time()) 

    # Calculate the checksum on the data and the dummy header. 
    # Append checksum to the header. 
    myChecksum = checksum(header + data)  
    if sys.platform == 'darwin': 
     myChecksum = socket.htons(myChecksum) & 0xffff 
     #Convert 16-bit integers from host to network byte order. 
    else: 
     myChecksum = htons(myChecksum) 

    packet = header + data 
    return packet 

def get_route(hostname): 
    timeLeft = TIMEOUT 
    for ttl in xrange(1,MAX_HOPS): 
     for tries in xrange(TRIES): 
      destAddr = socket.gethostbyname(hostname) 
      #Fill in start 
      # Make a raw socket named mySocket 
      mySocket = socket.socket(AF_INET, SOCK_RAW, getprotobyname("icmp")) 
      mySocket.bind(("", 12000)); 
      #Fill in end 
      mySocket.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl)) 
      mySocket.settimeout(TIMEOUT) 
      try: 
       d = build_packet() 
       mySocket.sendto(d, (hostname, 0)) 
       t = time.time() 
       startedSelect = time.time() 
       whatReady = select.select([mySocket], [], [], timeLeft) 
       howLongInSelect = (time.time() - startedSelect) 
       if whatReady[0] == []: # Timeout 
        print "* * * Request timed out." 

       recvPacket, addr = mySocket.recvfrom(1024) 
       print addr 
       timeReceived = time.time() 
       timeLeft = timeLeft - howLongInSelect 
       if timeLeft <= 0: 
        print "* * * Request timed out." 
      except socket.timeout: 
       continue 
      else: 
       #Fill in start 
       # Fetch the icmp type from the IP packet 
       print struct.calcsize("bbHHhd") 
       request_code, request_type, checksum, packet_id, \ 
        sequence, timeSent, data = struct.unpack("bbHHhd", recvPacket) 
       #Fill in end 

       if request_type == 11: 
        bytes = struct.calcsize("d") 
        timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0] 
        print " %d rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]) 
       elif request_type == 3: 
        bytes = struct.calcsize("d") 
        timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0] 
        print " %d rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]) 
       elif request_type == 0: 
        bytes = struct.calcsize("d") 
        timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0] 
        print " %d rtt=%.0f ms %s" % (ttl,(timeReceived -timeSent)*1000, addr[0]) 
        return 
       else: 
        print "error" 
        break 
      finally: 
       mySocket.close() 

get_route("www.google.com") 
+3

您是否檢查_recvPacket_的大小? – volcano

+0

@volcano,我得到64爲recvPacket的大小 – mowwwalker

+0

字符串必須包含格式所需的數據量(len(string)必須等於calcsize(fmt))。你的recvPacket = 64不等於你的fmt = 16。 –

回答

2

recvPacket比你的結構更大。如果你的結構是數據的第一部分,解包結構的剛字節:

pktFormat = 'bbHHhd' 
pktSize = struct.calcsize(pktFormat) 
... = struct.unpack(pktFormat, recvPacket[:pktSize]) 
+1

或者使用'struct.unpack_from',它可以避免複製,並且可以用來解碼緩衝區的其他部分。 –

+0

@JamesHenstridge請將此作爲回答。 –

5

struct.unpack功能需要您傳遞給它的數據完全匹配格式字符串的長度。

如果你有一個很大的緩衝區,而你只想解碼它的一部分,可以考慮使用struct.unpack_from函數。這需要一個額外的參數指定偏移量開始解碼,並接受緩衝區比格式字符串較大描述:

(request_code, request_type, checksum, packet_id, sequence, 
timeSent, data) = struct.unpack_from("bbHHhd", recvPacket, 0) 

,如果你想解析後的分組數據的其他部分進行解碼你會發現這個功能很有用頭。

相關問題