2012-11-19 3 views
4

내 컴퓨터 네트워킹 클래스의 경우 ICMP 프로토콜이 적용된 원시 소켓을 사용하여 Traceroute를 구현하려고합니다. 나는 패킷을 만들고 파이썬 구조체 클래스를 사용하여 응답 패킷을 풀어야한다. 패킷을 빌드하는 코드는 다음과 같습니다.struct : unpack Length 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, recvPacket의 크기는 64입니다. – 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) 

머리글.