Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

Extract Ethernet, IP header, TCP and payload from socket recv Python

How can I extract Extract Ethernet, IP header, TCP and payload from socket.recv in Python Right now I can obtain information above using 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:] 

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

When I use same function by a fragmented TCP packet and call socket.recv() I get errors when unpacking tcpheader.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks I recognized that socket.recv() returns a type str and socket.recvfrom() returns a tuple type, hence for socket.recv() I omitted packet = packet[0]. I will update code to handle TCP header to be variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...