I'm learning how to work with raw sockets in Linux. I'm trying to create a socket like that:
if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
perror("socket() failed");
exit(-1);
}
But all I got after launch is:
socket() failed: Operation not permitted
I know that only root can create raw sockets, but if I run it with SUID bit or sudo - the problem is the same. What's wrong? The system is Ubuntu 11.04.
Maybe I'm including needless headers?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
And I'm wondering - why SUID is useless?
My money on you not running your code correctly.
I've copied and pasted your exact code into an empty
main()
. I get the same error if I run it as myself, but it runs correctly undersudo
. This is on Ubuntu.The code:
Run as myself:
Run as root:
Header will not affect it in anyway.
Even if you would be adding some more unnecessary files it will not affect the working of the program.
according to man: Only processes with an effective user ID of 0 or the CAP_NET_RAW capability are allowed to open raw sockets
So you could run you application with sudo as was suggested below or set CAP_NET_RAW capability to it (actually you'll need CAP_NET_ADMIN too):
Details could be found at http://ftp.kernel.org/pub/linux/libs/security/linux-privs/kernel-2.4/capfaq-0.2.txt