Linux – dump tcp connections without tcpdump

linuxtcp

On a centos box, I like to dump tcp connections – I would like to see if a server tries to send requests to a certain IP. Usually tcpdump would do the trick – but tcpdump is not installed, and installing software is not an option (because of company policy). I am afraid netstat will not show me a single request.

So I was wondering what other options I have. I do have root access on the server.

Best Answer

Surely you have python?

from socket import * 
from struct import unpack 
import sys 

INTERFACE = "eth0"
TARGET = "8.8.8.8" 

if __name__ == "__main__": 
  sock = socket(AF_PACKET, SOCK_DGRAM, 0x0800) 
  sock.bind((INTERFACE, 0x0800)) 
  while True: 
    data = sock.recvfrom(1500, 0)[0] 
    ip = inet_ntop(AF_INET, data[12:16]) 
    if ip == TARGET: 
      print "GOT TARGET" 
      sys.exit(1)

This will exit with "GOT TARGET" providing the IP address coming back matches. Since TCP has to send something back during a handshake, this should catch anything from a specific target address. It doesn't care if the protocol is TCP or UDP though (nor do I check).

Dont forget to change TARGET and INTERFACE.