LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Kernel (https://www.linuxquestions.org/questions/linux-kernel-70/)
-   -   Raw Socket in Kernal space (https://www.linuxquestions.org/questions/linux-kernel-70/raw-socket-in-kernal-space-787301/)

bostan 02-05-2010 04:02 PM

Raw Socket in Kernal space
 
Hi All,
Is it possible to use create a raw socket in kernel space ? If possible is there any snippet/code which I can use to enhance my application ?
Any help is highly appreciated.
-Thanks in advance

irmin 02-05-2010 04:17 PM

Hi,

it is possible to create a raw socket it kernel mode using the sock_create function defined in net/socket.c in the kernel sources.

Code:

#include <linux/net/net.h>

...

struct socket * sockptr;
int error;

if((error = sock_create( PF_INET, SOCK_RAW, 6, &sockptr )) < 0)
 {
  printk(KERN_ERR "cannot create raw socket\n");
  return -EIO;
 }

/* use sockptr */

kernel_sock_shutdown( sockptr, SHUT_RDWR );

But why do you want to create a socket in kernel space? Are you writing some kind of kernel module?

bostan 02-05-2010 04:41 PM

Thanks Irmin,
Does this mean I need to call setsockopt to inform the kernal not to add the headers and create my own ip pkt ? Or there is any equivalant system call for it ?
-Thanks

irmin 02-05-2010 04:49 PM

If you do not want the IPv4 layer to create an IP header, you have to set the option IP_HDRINCL. (see man 7 raw)
Use kernel_setsockopt for this. Basically the kernel socket interface is the same as the system calls.

See <kernel-source>/include/linux/net.h for details.

But I wonder, if this really what you want to do, since sending and receiving raw ip packets can also be done using socket/setsockopt/sendmsg/recvmsg system calls.

bostan 02-08-2010 09:22 AM

Thanks Irmin,
This was helpful. I really appreciate it.

BTW what kind of header files I need ? I tried these hdr files but its not compiling and giving me error of files not found. I tried to compile this on Linux machine as well as Vmware.
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <linux/net/net.h>
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>


-Thanks

bostan 02-08-2010 10:22 AM

how to build the code with kernal system calls
 
Hi,
I have created the foo.c file for socket. I am calling the sock_sendmsg and etc as kernal system calls directly. I have included the files which are needed for this calls.
My question is should I build this foo.c using "gcc foo.c" or I have to build this file in kernal mode and than load the kernal using insmode ?
Any help is good.
-Thanks


All times are GMT -5. The time now is 10:17 AM.