从socket recv Python中提取以太网,IP头,TCP和有效负载

时间:2013-11-13 18:21:09

标签: python sockets tcp

如何从Python中的 socket.recv 中提取Extract Ethernet,IP header,TCP和payload 现在我可以使用 socket.recvfrom()

获取上述信息
    packet = s.recvfrom(NETWORK_MAX_SIZE)
    packet = packet[0] 
    #parse ethernet header
    eth_length = 14
    eth_header = packet[:eth_length]
    eth = unpack('!6s6sH' , eth_header)
    eth_protocol = socket.ntohs(eth[2])
    t = iph_length + eth_length
    tcp_header = packet[t:t+20]
    #now unpack them :)
    tcph = unpack('!HHLLBBHHH' , tcp_header)
    source_port = tcph[0]
    dest_port = tcph[1]
    sequence = tcph[2]
    acknowledgement = tcph[3]
    doff_reserved = tcph[4]
    tcph_length = doff_reserved >> 4
    h_size = eth_length + iph_length + tcph_length * 4
    data_size = len(packet) - h_size
    #get data from the packet
    data = packet[h_size:] 

参考: http://www.binarytides.com/python-packet-sniffer-code-linux/

当我通过碎片TCP数据包使用相同的功能并调用 socket.recv()时,解压缩tcpheader时会出错。

谢谢

1 个答案:

答案 0 :(得分:1)

谢谢我认识到 socket.recv()返回一个str类型, socket.recvfrom()返回一个元组类型,因此对于socket.recv()我省略了packet = packet [0]。 我将更新代码以处理TCP头是可变的。