Hello Everyone
I am developing a module which I will load with insmod... for my linux
kernel. In this module I want to be able to send and recieve UDP
packets. After some trial and error I concluded that the normal
socket, sendto ....... API's was not an option since each time I
loaded my module I got unreference symbols.... Therefore I shopped
around and it seems that sock_create, sock_sendmsg and sock_recvmsg is
the way to go. I have written the following code and it compiles and I
can insert it as well using insmod:
struct socket *udpsock;
u32 get_address(char *ifname)
{
struct net_device *dev;
u32 addr;
if ((dev = __dev_get_by_name(ifname)) == NULL)
return -ENODEV;
else
printk("Found device\n");
addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
if (!addr)
printk("Specify IP address on multicast interface.\n");
return addr;
}
int init_module(void)
{
int error;
struct sockaddr_in sin;
struct msghdr udpmsg;
mm_segment_t oldfs;
struct iovec iov;
char buffer[] = "A small test msg";
printk("Elvis has entered the building\n");
error = sock_create(PF_INET, SOCK_DGRAM, 0, &udpsock);
if (error<0)
{
printk("Error during creation of socket; terminating\n");
return -1;
}
//memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(9090);
sin.sin_addr.s_addr = get_address("eth0");
error = udpsock->ops->bind(udpsock,(struct sockaddr
*)&sin,sizeof(sin));
if (error<0)
{
printk("Error binding socket");
return -1;
}
iov.iov_base = (void *)buffer;
iov.iov_len = strlen(buffer);
udpmsg.msg_name = 0;
udpmsg.msg_namelen = 0;
udpmsg.msg_iov = &iov;
udpmsg.msg_iovlen = 1;
udpmsg.msg_control = NULL;
udpmsg.msg_controllen = 0;
udpmsg.msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL;
oldfs = get_fs(); set_fs(KERNEL_DS);
error = sock_sendmsg(udpsock, &udpmsg, strlen(buffer));
set_fs(oldfs);
if(error < 0)
printk("Error when sendimg msg\n");
return 0;
}
void cleanup_module(void)
{
sys_close(udpsock);
printk("Elvis has left the building\n");
}
However it does not work


The socket is created and the bind works
fine as well but the msg is not sent out: error is < 0 after
sock_sendmsg. I feel that I am doing something wrong when I construct
the message but I am not sure what it is.
I also have some doubts about the following code:
sin.sin_addr.s_addr = get_address("eth0");
this is something I had to try since I dont seem to be able to convert
IP address into the correct format. In a normal program I would use:
sin.sin_addr.s_addr = inet_addr("192.168.1.4");
but it does not work here. So my questions are as follows:
1. How do I convert an IP address into the correct format when working
with modules?
2. Have I constructed the message that I send correctly or is there
anything wrong with it.
I would also welcome general comments on my code as well so that I can
find out what I am doing wrong.
Regards
Andreas