- #!/usr/bin/env python
- # ---------------------------------------------------------
- import sys,time, math
- # ---------------------------------------------------------
- class ProcReader:
- """
- Format of /proc/net/tcp
- 46: 010310AC:9C4C 030310AC:1770 01
- | | | | | |--> connection state
- | | | | |------> remote TCP port number
- | | | |-------------> remote IPv4 address
- | | |--------------------> local TCP port number
- | |---------------------------> local IPv4 address
- |----------------------------------> number of entry
- 00000150:00000000 01:00000019 00000000
- | | | | |--> number of unrecovered RTO timeouts
- | | | |----------> number of jiffies until timer expires
- | | |----------------> timer_active (see below)
- | |----------------------> receive-queue
- |-------------------------------> transmit-queue
- 1000 0 54165785 4 cd1e6040 25 4 27 3 -1
- | | | | | | | | | |--> slow start size threshold,
- | | | | | | | | | or -1 if the threshold
- | | | | | | | | | is >= 0xFFFF
- | | | | | | | | |----> sending congestion window
- | | | | | | | |-------> (ack.quick<<1)|ack.pingpong
- | | | | | | |---------> Predicted tick of soft clock
- | | | | | | (delayed ACK control data)
- | | | | | |------------> retransmit timeout
- | | | | |------------------> location of socket in memory
- | | | |-----------------------> socket reference count
- | | |-----------------------------> inode
- | |----------------------------------> unanswered 0-window probes
- |---------------------------------------------> uid
- """
- def __init__(self,port):
- self.port = port
- self.f = open( "/proc/net/tcp" )
- self.porthex = ":%04X" % (port)
- def read(self):
- now = time.time()
- self.f.seek(0)
- lines = self.f.readlines()
- n, sum_tx, sum_rx = 0, 0, 0
- for line in lines:
- t = line.split()
- if not t[1].endswith(self.porthex):
- continue
- x = t[4].split(':')
- n += 1
- sum_tx += int(x[0],16)
- sum_rx += int(x[1],16)
- return now,sum_tx,sum_rx,n
- # ---------------------------------------------------------
- def main(port):
- """
- Display: timestamp
- nb sockets
- tx = pending data to transmit for all connections (bytes)
- rx = pending data to receive for all connections (bytes)
- running moving average of tx (1 sec, 4 points)
- running moving average of rx (1 sec, 4 points)
- """
- p = ProcReader(port)
- t, tx, rx = 0.0, 0.0, 0.0
- print "%16s %6s %12s %12s %16s %16s" % ( "Timestamp", "Nb", "TX bytes", "RX bytes", "TX RMA", "RX RMA" )
- while 1:
- x = p.read()
- tx = (3*tx+x[1])/4
- rx = (3*rx+x[2])/4
- if int(x[0]) != t:
- print "%16.3f %6d %12d %12d %16.3f %16.3f" % (x[0],x[3],x[1],x[2],tx,rx)
- t = int(x[0])
- time.sleep(0.250-(time.time()-x[0]))
- # ---------------------------------------------------------
- if len(sys.argv) != 2:
- sys.stderr.write( "Usage: %s port\n" % (sys.argv[0]) )
- sys.exit( -1 )
- main( int(sys.argv[1]) )
- # ---------------------------------------------------------