Raw socket in C

Asked

Viewed 139 times

0

I’m looking to make a Sniffer in C using the Socket API.

I saw that a good solution was to use the raw socket:

sock_raw = socket(AF_INET , SOCK_RAW , 'Tipo do protocolo aqui UDP/TCP/ICMP');

But I didn’t understand the foundation of the raw socket. Could anyone explain how it works ? In what layers it acts ?

And in the recvfrom :

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                 struct sockaddr *src_addr, socklen_t *addrlen)

What is the real purpose of *buf and of flags ?

And if anyone can show you how to get a specific field of a package received with that recvfrom I thank you. Because I need to make a Sniffer with this API and take the message that is transmitted by a package ( an integer number and a char vector transmitted by a socker for example).

2 answers

0

SOCK_RAW allows both receiving and sending packages. The main utility of SOCK_RAW is to implement new transport protocols in userspace (outside the kernel). For example, a program that uses ICMP packages like ping has to be implemented using this type of socket.

To sniffing you will be much better served using libpcap, which is even portable. Another advantage of libpcap is efficiency: you can filter for many parameters beyond the protocol, and this BPF filter is literally compiled within the kernel for maximum efficiency.

But yes, a SOCK_RAW socket can be used to "sniffar" packages.

The buf parameter is a pointer to a buffer (can be a char bla variable[4096]) with enough space to receive packets.

The internal format of the data you will find in this buffer varies according to the protocol you chose as "filter". For example, if the protocol is IPPROTO_RAW, you will receive all IP packets, so the beginning of the buffer will contain the IP header, which you will need to parse to find the transport protocol. If you use IPPROTO_UDP, the beginning of the buffer will contain the UDP header, but not the IP header. And if you use htons(ETH_P_ALL), you will receive the entire Ethernet package, the beginning of the buffer will have the link layer header.

The flags parameter can be 0 or it can receive a value that modifies the behavior of the function. There are many of them, for example the value MSG_DONTWAIT makes the function return immediately if there is a package ready to be read (ie the function operates in non-blocking mode).

This page has several examples of SOCK_RAW usage: http://www.pdbuchan.com/rawsock/rawsock.html

-1

If you are an extreme high-level hacker then you can think about creating a Sniffer using raw sockets. Otherwise you can do like most people who writes sniffers and use a capture library, like the libpcap.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.