2

I want to write a packet sniffer that sniffs all incoming TCP packets.In one of the examples that I was looking instead of using SOCK_RAW instead of SOCK_STREAM?

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
except socket.error as e:
    print('Socket creation failed. Error Code {} Message {}'.format(str(e[0]),str(e[1])))
    sys.exit()

#Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
packet = s.recvfrom(65565)

1) In the above case can I use SOCK_STREAM instead of SOCK_RAW. 2) What does recvfrom(65565) mean ? Does it mean recvfrom all TCP ports instead of a specific TCP port?

1 Answer 1

2
  1. If you use SOCK_STREAM instead of SOCK_RAW you won't be able to read the protocols headers, but only the data transmitted via TCP. In the other hand, SOCK_RAW will give you access to the full packet headers. In your case, as you want to build your own protocol analyzer (sniffer), SOCK_RAW should be your choice.

  2. The method definition for recvfrom is:

    socket.recvfrom(bufsize[, flags])

    Receive data from the socket. The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data

This method simply receives maximum bufsize bytes from the socket.

Sign up to request clarification or add additional context in comments.

2 Comments

recvfrom() will recieve data from all tcp ports? how does the socket abstraction tie in with the ports ?
You don't receive data from a port with raw sockets, since ports are a concept of TCP and UDP. The socket will receive all packets with the specified IPPROTO_* (in your case, IPPROTO_TCP).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.