python - TCP段丢失

时间:2015-01-05 11:53:16

标签: python sockets tcp packets

我使用以下代码来捕获TCP数据包。我试图匹配python脚本和tcpdump之间的结果;有时我注意到python脚本丢失了TCP数据包。我错了什么?

import socket
from struct import *
s = socket.socket(socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))

   while True:
           try:
                   packet = s.recvfrom(65535)
           except:
                   print "ERROR"
           packet = packet[0]
           eth_length = 14
           eth_header = packet[:eth_length]
           eth = unpack('!6s6sH' , eth_header)
           eth_protocol = socket.ntohs(eth[2])

           if eth_protocol == 8 :
                   ip_header = packet[eth_length:20+eth_length]
                   iph = unpack('!BBHHHBBH4s4s' , ip_header)
                   version_ihl = iph[0]
                   version = version_ihl >> 4
                   ihl = version_ihl & 0xF
                   iph_length = ihl * 4
                   ttl = iph[5]
                   protocol = iph[6]
                   s_addr = socket.inet_ntoa(iph[8]);
                   d_addr = socket.inet_ntoa(iph[9]);

                   if protocol == 6 :
                           t = iph_length + eth_length
                           tcp_header = packet[t:t+20]
                           tcph = unpack('!HHLLBBHHH' , tcp_header)
                           seq = tcph[2]
                           ack = tcph[3]
                           flag = tcph[5]

                           print str(s_addr) + " " + str(d_addr) + " " + str(seq) + " " + str(ack) + " " + str(flag)
  • Tcpdump输出

xxx.xxx.xxx.xxx.80> yyy.yyy.yyy.yyy.44430:Flags [。],cksum 0x39ba(正确),seq 2282440133:2282441593,ack 1516508541,win 64240,length 1460

xxx.xxx.xxx.xxx.80> yyy.yyy.yyy.yyy.44430:Flags [。],cksum 0x67fe(正确),seq 2282441593:2282443053,ack 1516508541,win 64240,length 1460

xxx.xxx.xxx.xxx.80> yyy.yyy.yyy.yyy.44430:Flags [P.],cksum 0xf490(正确),seq 2282443053:2282444373,ack 1516508541,win 64240,length 1320

yyy.yyy.yyy.yyy.44430> xxx.xxx.xxx.xxx.80:标志[。],cksum 0x547a(正确),seq 1516508541,ack 2282444373,win 65535,length 0

xxx.xxx.xxx.xxx.80> yyy.yyy.yyy.yyy.44430:Flags [。],cksum 0x154c(正确),seq 2282444373:2282445833,ack 1516508541,win 64240,length 1460

xxx.xxx.xxx.xxx.80> yyy.yyy.yyy.yyy.44430:Flags [。],cksum 0xf11c(正确),seq 2282445833:2282447293,ack 1516508541,win 64240,length 1460

yyy.yyy.yyy.yyy.44430> xxx.xxx.xxx.xxx.80:标志[。],cksum 0x4912(正确),seq 1516508541,ack 2282447293,win 65535,length 0

  • Python输出

xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 2282440133 1516508541 16

xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 2282444373 1516508541 16

xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 2282450101 1516508541 16

xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 2282451561 1516508541 16

xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 2282457261 1516508541 16

xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy 2282458721 1516508541 16

yyy.yyy.yyy.yyy xxx.xxx.xxx.xxx 1516508541 2282460181 16

0 个答案:

没有答案