我通过检索python套接字编写自己的数据包嗅探器 数据包信息,例如源ip,源端口,目标ip, 设计端口,TTL,标志(SYN,ACK,FIN,RST,PSH,URG)等。
对于IPv4,我能够根据各自的位置对数据包进行拆包,其结果类似于我在tshark中看到的结果。参见下面的代码:
IPv4_UNPACK_PATTERN = '!BBHHHBBH4s4s'
IPv6_UNPACK_PATTERN = '!4sHBB16s16s'
IPv4_HDR_LEN = 20
IPv6_HDR_LEN = 40
TCP_HDR_LEN = 20
ETH_HDR_LEN = 14
# IP ATTRIBUTES
IP_VERSION_POS = 0
IP_TOS_POS = 1
IP_LENGTH_POS = 2
IP_IDENTIFICATION_POS = 3
IP_FRAGMENT_OFFSET_POS = 4
IP_TTL_POS = 5
IP_PROTOCOL_POS = 6
IP_HDR_CHCKSUM_POS = 7
IP_SRC_ADDR_POS = 8
IP_DST_ADDR_POS = 9
TCP_FLAG_POS = 5
TCP_WINDOW_POS = 6
# main program:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
packet = s.recvfrom(SOCKET_BUFF_SIZE)
pkt_type = extract_type(packet)
ip_header(packet, pkt_type)
# this function extracts the information from pkt
def ip_header(pkt, pkt_type):
if pkt_type=='ipv4':
data = unpack(IPv4_UNPACK_PATTERN, pkt[ETH_HDR_LEN:ETH_HDR_LEN + IPv4_HDR_LEN])
version = data[IP_VERSION_POS]
total_length = data[IP_LENGTH_POS]
ttl = data[IP_TTL_POS]
protocol = data[IP_PROTOCOL_POS]
ip_header = (version & 0xF) * 4
start_pos = ETH_HDR_LEN + IPv4_HDR_LEN
# Unpacking TCP
tcp_obj = unpack(TCP_UNPACK_PATTERN, data[start_pos:start_pos + TCP_HDR_LEN])
tcp_flag = tcp_obj[TCP_FLAG_POS]
window = str(tcp_obj[TCP_WINDOW_POS])
else: # ipv6
data = unpack(IPv6_UNPACK_PATTERN, pkt[ETH_HDR_LEN:ETH_HDR_LEN + IPv6_HDR_LEN])
# what bit positions to be used here for ipv6?
但是对于IPv6数据包,我不知道ipv6字段的正确位位置。
任何人都可以将我指向说明以下字段的ipv6数据包的位位置的文档: