Python/2.7 information

raw 소켓 파악하기 2.

qkqhxla1 2016. 3. 7. 10:34

아래 글에서 에러 발견. 아직 제대로 읽지 말 것.


raw 소켓으로 이전 http://qkqhxla1.tistory.com/532 에서 하려했던 tcp 통신을 구현해보자. 앞에서 해봤던 icmp는 그냥 내가 한방향으로 보내기만 하면 와이어샤크에서 잡아서 볼수 있었는데, 이건 아니다. tcp는 3 핸드 쉐이킹을 한다. 이걸 다 구현해야 될것 같다.(아직 해보지는 않음.) 근데 3핸드쉐이킹이던 뭐던 생각하기 전에 일단 tcp패킷 자체를 만들어야 한다. 

TCP/IP이론은 예전에 수업에서 다 배웠었다. 가물가물해가며 찾은 결과 TCP는 IP위에 올라간다. 올라간다.? 는 말은 알고 있지만 구현하려면 뭐 어떻게 구현해야 한다는겨? 또 여기저기 찾아본결과 올라간다는 말은 구현하면 IP헤더 + TCP헤더 이런형식으로 구현하면 된다고 한다.


일단 그럼 IP부터 구현해보자. IP 패킷 구조다. 여기에도 자세한 정보가 있다.

http://networksorcery.com/enp/protocol/ip.htm

앞에서 ICMP를 구현해보았기에 코드 수정이 더 쉬웠다.

# -*- encoding: cp949 -*-
import socket
import struct

def checksum(data):
    s = 0
    n = len(data) % 2
    for i in range(0, len(data)-n, 2):
        s+= ord(data[i]) + (ord(data[i+1]) << 8)
    if n:
        s+= ord(data[i+1])
    while (s >> 16):
        s = (s & 0xFFFF) + (s >> 16)
    s = ~s & 0xFFFF
    return s

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)

packet = '';
 
source_ip = '192.168.1.103'
dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com')
 
# ip header fields
ip_ver = 4
ip_ihl = 5
ip_tos = 1
ip_tot_len = 0  # kernel will fill the correct total length
ip_id = 54321   #Id of this packet
ip_frag_off = 0
ip_ttl = 255
ip_proto = socket.IPPROTO_TCP
ip_check = 0    # kernel will fill the correct checksum
ip_saddr = socket.inet_aton ( source_ip )   #Spoof the source ip address if you want to
ip_daddr = socket.inet_aton ( dest_ip )
 
ip_ihl_ver = (ip_ver << 4) + ip_ihl
 
# the ! in the pack format string means network order
real_chksum = checksum(struct.pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr))
ip_header = struct.pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, real_chksum, ip_saddr, ip_daddr)

s.sendto(ip_header,('192.168.8.1',0))

윈도우에서 관리자모드로 실행시 잘 도착했음을 확인할수 있다. 와이어샤크에서도 IPV4패킷으로 인식한다.


이제 tcp를 덧붙여보자. tcp패킷 구조다.


'Python > 2.7 information' 카테고리의 다른 글

Iterator, Generator, Decorator  (0) 2016.06.24
함수 리팩토링 관련 모듈들.  (0) 2016.06.23
raw 소켓 파악하기 1.  (0) 2016.03.07
파이썬 내부구조 이해하기. 2.x  (0) 2016.02.27
python lambda function  (0) 2016.02.08