IPV4 RAW AF INET UDP server client program with Epoll system call
In this program, you are going to learn
How to create a Socket ?
How to send a data ?
How to recv a data ?
How to use socket APIs ?
Let us answer few basic questions in this socket
What does socket(AF_INET, SOCK_RAW, IPPROTO_UDP)
do?
See Answer
This call creates a raw socket in the AF_INET
address family for direct access to UDP packets.
When would I use SOCK_RAW
sockets with IPPROTO_UDP
?
See Answer
This combination is used for tasks like packet sniffing, crafting custom protocols, or low-level UDP packet manipulation.
Can SOCK_RAW
sockets be used for regular UDP communication?
See Answer
While technically possible, it’s not recommended. Higher-level APIs are more suitable for standard UDP communication.
What is the difference between IPPROTO_UDP
and SOCK_RAW
for UDP communication?
See Answer
IPPROTO_UDP
specifies the transport protocol (UDP), while SOCK_RAW indicates a raw socket,
providing more control over UDP packet content.
What are common issues when working with raw UDP sockets?
See Answer
Common issues include permission errors, endianness mismatches, and improper packet handling.
How do I handle errors when using raw UDP sockets?
See Answer
Use error codes returned by system calls like socket and sendto for error handling. Log and handle errors gracefully.
Can raw UDP sockets be used for both sending and receiving data?
See Answer
Yes, raw UDP sockets can be used for both sending and receiving UDP packets.
Why is it important to check the return value of sendto() and recvfrom() in socket programming?
See Answer
It detects issues such as network errors or closed connections.
What is the primary purpose of the epoll system call?
See Answer
To efficiently monitor multiple file descriptors for I/O events
What types of file descriptors can be monitored using epoll?
See Answer
sockets, files, timerfd, socketpair, message_queue, Namedpipes and shared_memory.
What data structure is used by epoll to store events?
See Answer
Hash table
How do you handle errors when using the epoll system call?
See Answer
Check the return value for -1 to detect errors, Use perror to print error messages.
How does epoll handle a set of file descriptors with different states (e.g., reading, writing, exception)?
See Answer
- Create the epoll Instance:
Before monitoring file descriptors, the application creates an epoll instance using the epoll_create system call.
int epoll_fd = epoll_create1(0);
- Register File Discriptors:
The application registers file descriptors with the epoll instance using the epoll_ctl system call. It specifies the file descriptor, the events it is interested in (EPOLLIN for readability, EPOLLOUT for writability, etc.), and a user-defined data associated with the file descriptor.
struct epoll_event event;
event.events = EPOLLIN | EPOLLOUT; // Interested in readability and writability
event.data.fd = my_file_descriptor; // File descriptor to monitor
epoll_ctl(epoll_fd, EPOLL_CTL_ADD, my_file_descriptor, &event);
- Wait for Events:
The application enters a loop where it calls epoll_wait to wait for events. This call blocks until one or more registered file descriptors become ready or until a timeout occurs.
#define MAX_EVENTS 10
struct epoll_event events[MAX_EVENTS];
int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, timeout_ms);
- Modify or Remove File Descriptors:
The application can dynamically modify or remove file descriptors from the epoll set using the epoll_ctl system call. For example, to modify events for an existing file descriptor:
struct epoll_event new_event;
new_event.events = EPOLLOUT; // Modify to be interested in writability
epoll_ctl(epoll_fd, EPOLL_CTL_MOD, my_file_descriptor, &new_event);
To remove a file descriptor from the epoll set:
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, my_file_descriptor, NULL);
How does epoll Checking Ready File Descriptors?
See Answer
After epoll_wait returns, the application iterates through the returned events to identify which file descriptors are ready and for what types of events.
for (int i = 0; i < num_events; ++i) {
if (events[i].events & EPOLLIN) {
// File descriptor i is ready for reading
}
if (events[i].events & EPOLLOUT) {
// File descriptor i is ready for writing
}
// Check other events if needed (e.g., EPOLLERR, EPOLLHUP)
}
What does it mean if epoll returns 0?
See Answer
No file descriptors are ready within the specified timeout.
There are many functions used in socket. We can classify those functions based on functionalities.
Create Socket
Epoll create1
Epoll_ctl
Epoll_wait
Recvfrom data_packet
Sendto data_packet
Close socket
socket()
is used to create a new socket. For example,
sock_fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
epoll_create1()
creating an epoll instance using epoll_create1, The size parameter is an advisory hint for the kernel regarding the number of file descriptors expected to be monitored, For example,
epoll_fd = epoll_create1(0);
epoll_ctl()
After creating an epoll instance, file descriptors are added to it using epoll_ctl, For example,
ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock_fd, &event);
epoll_wait()
The application then enters a loop where it waits for events using epoll_wait, For example,
ready_fds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
recvfrom
is commonly used with sockets, where communication is connectionless. it provides information about the source (sender) of the data, including the sender’s IP address and port number. For example,
ret = recvfrom(sock_fd, recvbuffer, (sizeof(struct iphdr) + sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, &length);
sendto
is used to send the encoded message to the specified server address and port using a socket. For example,
ret = sendto(sock_fd, buffer, (sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, sizeof(struct sockaddr_in));
close
is used to close the socket To free up system resources associated with the socket. For example,
(void)close(sock_fd);
See the full program below,
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <linux/udp.h> /* UDP Header */
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <linux/ip.h>
#include <sys/epoll.h>
#define MAX_EVENTS 5
struct sockaddr_in
*clientaddr = NULL;
int sock_fd = -1;
int epoll_fd = -1;
int SERVPORT=20000;
int DESTPORT=20001;
struct pseudo_iphdr {
unsigned int source_ip_addr;
unsigned int dest_ip_addr;
unsigned char fixed;
unsigned char protocol;
unsigned short udp_len;
};
unsigned short in_cksum (
uint16_t * addr, int len)
{
int nleft = len;
unsigned int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
if (nleft == 1) {
*(unsigned char *) (&answer) =
* (unsigned char *) w;
sum += answer;
}
sum = (sum >> 16) +
(sum & 0xffff);
sum += (sum >> 16);
answer = (unsigned short) ~sum;
return (answer);
}
void interrupt_handler (
int signum)
{
(void)close(sock_fd);
free(clientaddr);
exit(0);
}
void validate_convert_addr(
char *ip_str,
struct sockaddr_in *sock_addr)
{
if (ip_str == NULL) {
perror("Invalid ip_str\n");
exit(EXIT_FAILURE);
}
if (sock_addr == NULL) {
perror("Invalid sock_addr\n");
exit(EXIT_FAILURE);
}
printf("IP Address: %s\n", ip_str);
if (inet_pton(AF_INET, ip_str,
&(sock_addr->sin_addr)) <= 0) {
perror("Invalid address\n");
exit(EXIT_FAILURE);
}
}
void main (int argc, char *argv[])
{
socklen_t length;
char buffer[1024] = {0};
unsigned char
recvbuffer[1024] = {0};
char *string =
"Hello client\n";
struct udphdr *udp_hdr = NULL;
char *string_data = NULL;
char *recv_string_data = NULL;
char *csum_buffer = NULL;
struct pseudo_iphdr
csum_hdr;
int ready_fds, ret;
struct epoll_event
events[MAX_EVENTS];
struct epoll_event event;
signal (SIGINT,
interrupt_handler);
signal (SIGTERM,
interrupt_handler);
if (argc != 2) {
printf("%s<ip-addr>\n",
argv[0]);
exit(EXIT_FAILURE);
}
sock_fd = socket(AF_INET,
SOCK_RAW,
IPPROTO_UDP);
if (sock_fd < 0) {
printf("create a socket\n");
exit(0);
}
clientaddr = (struct sockaddr_in *)malloc(
sizeof(struct sockaddr_in));
if (clientaddr == NULL) {
printf("allocate memory\n");
goto end;
}
clientaddr->sin_family = AF_INET;
clientaddr->sin_port =
htons(DESTPORT);
validate_convert_addr(argv[1],
clientaddr);
memset(buffer, 0,
sizeof(buffer));
string_data = (char *)
(buffer + sizeof(struct udphdr));
strncpy(string_data,
string, strlen(string));
udp_hdr = (struct udphdr *)buffer;
udp_hdr->source = htons(SERVPORT);
udp_hdr->dest = htons(DESTPORT);
udp_hdr->len = htons(
sizeof(struct udphdr));
csum_buffer = (char *)calloc((
sizeof(struct pseudo_iphdr) +
sizeof(struct udphdr) +
strlen(string_data)), sizeof(char));
if (csum_buffer == NULL) {
printf("allocate csum buffer\n");
goto end1;
}
csum_hdr.source_ip_addr =
inet_addr("127.0.0.1");
csum_hdr.dest_ip_addr =
inet_addr("127.0.0.1");
csum_hdr.fixed = 0;
csum_hdr.protocol = IPPROTO_UDP;
csum_hdr.udp_len = htons(
sizeof(struct udphdr) +
strlen(string_data) + 1);
memcpy(csum_buffer,
(char *)&csum_hdr,
sizeof(struct pseudo_iphdr));
memcpy(csum_buffer +
sizeof(struct pseudo_iphdr), buffer,
(sizeof(struct udphdr) +
strlen(string_data) + 1));
udp_hdr->check = (in_cksum(
(unsigned short *) csum_buffer,
(sizeof(struct pseudo_iphdr)+
sizeof(struct udphdr) +
strlen(string_data) + 1)));
printf("checksum is %x\n",
udp_hdr->check);
free (csum_buffer);
epoll_fd = epoll_create1(0);
if (epoll_fd < 0) {
perror("Epoll creation failed");
exit(EXIT_FAILURE);
}
event.events = EPOLLIN;
event.data.fd = sock_fd;
ret = epoll_ctl(epoll_fd,
EPOLL_CTL_ADD, sock_fd, &event);
if (ret < 0) {
perror("Epoll_ctl failed");
exit(EXIT_FAILURE);
}
while (1) {
ready_fds = epoll_wait(epoll_fd,
events, MAX_EVENTS, -1);
if (ready_fds < 0) {
perror("Epoll wait failed");
exit(EXIT_FAILURE);
}
if (events[0].data.fd ==
sock_fd) {
memset(recvbuffer, 0,
sizeof(recvbuffer));
ret = recvfrom(sock_fd, recvbuffer,
(sizeof(struct iphdr) +
sizeof(struct udphdr)+
strlen(string_data)+1), 0,
(struct sockaddr *)clientaddr,
&length);
if (ret < 0) {
printf("recv Message\n");
goto end1;
}
udp_hdr = (struct udphdr *)
(recvbuffer +
sizeof (struct iphdr));
recv_string_data = (char *)
(recvbuffer +
sizeof (struct iphdr) +
sizeof (struct udphdr));
if (SERVPORT ==
ntohs(udp_hdr->source)) {
printf("Received :%s\n",
recv_string_data);
}
ret = sendto(sock_fd, buffer,
(sizeof(struct udphdr)+
strlen(string_data)+1), 0,
(struct sockaddr *)clientaddr,
sizeof(struct sockaddr_in));
if (ret < 0) {
printf("send Message\n");
goto end1;
}
}
}
end1:
free (clientaddr);
end:
(void)close(sock_fd);
return;
}
$ gcc -o server server.c
$ sudo ./server 127.0.0.1
IP Address: 127.0.0.1
checksum is 53fc
Received :Hello server
Received :Hello server
Received :Hello server
Received :Hello server
Received :Hello server
Received :Hello server
Received :Hello client
Received :Hello server
Received :Hello client
Received :Hello server
Received :Hello client
^C
There are many functions used in socket. We can classify those functions based on functionalities.
Create Socket
Epoll create1
Epoll_ctl
Epoll_wait
Sendto data_packet
Recvfrom data_packet
Close socket
socket
is used to create a new socket. For example,
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
epoll_create1()
creating an epoll instance using epoll_create1, The size parameter is an advisory hint for the kernel regarding the number of file descriptors expected to be monitored, For example,
epoll_fd = epoll_create1(0);
epoll_ctl()
After creating an epoll instance, file descriptors are added to it using epoll_ctl, For example,
ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &event);
epoll_wait()
The application then enters a loop where it waits for events using epoll_wait, For example,
ready_fds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
sendto
is used to send the encoded message to the specified server address and port using a socket. For example,
ret = sendto(sockfd, buffer, (sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, sizeof(struct sockaddr_in));
recvfrom
is commonly used with sockets, where communication is connectionless. it provides information about the source (sender) of the data, including the sender’s IP address and port number. For example,
ret = recvfrom(sockfd, recvbuffer, (sizeof(struct iphdr) + sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, &length);
close
is used to close the socket To free up system resources associated with the socket. For example,
(void)close(sockfd);
See the full program below,
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <linux/udp.h> /* UDP Header */
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <linux/ip.h>
#include <sys/epoll.h>
#define MAX_EVENTS 2
struct sockaddr_in
*clientaddr = NULL;
int sockfd = -1;
int epoll_fd = -1;
int SERVPORT=20000;
int DESTPORT=20001;
struct pseudo_iphdr {
unsigned int source_ip_addr;
unsigned int dest_ip_addr;
unsigned char fixed;
unsigned char protocol;
unsigned short udp_len;
};
unsigned short in_cksum (
uint16_t * addr, int len)
{
int nleft = len;
unsigned int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
if (nleft == 1) {
*(unsigned char *) (&answer) = *
(unsigned char *) w;
sum += answer;
}
sum = (sum >> 16) +
(sum & 0xffff);
sum += (sum >> 16);
answer = (unsigned short) ~sum;
return (answer);
}
void interrupt_handler (
int signum)
{
(void)close(sockfd);
free(clientaddr);
exit(0);
}
void validate_convert_addr(
char *ip_str,
struct sockaddr_in *sock_addr)
{
if (ip_str == NULL) {
perror("Invalid ip_str\n");
exit(EXIT_FAILURE);
}
if (sock_addr == NULL) {
perror("Invalid sock_addr\n");
exit(EXIT_FAILURE);
}
printf("IP Address: %s\n", ip_str);
if (inet_pton(AF_INET, ip_str,
&(sock_addr->sin_addr)) <= 0) {
perror("Invalid address\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
socklen_t length;
char buffer[1024] = {0};
unsigned char recvbuffer[1024] =
{0};
char *string =
"Hello server\n";
struct udphdr *udp_hdr = NULL;
char *string_data = NULL;
char *recv_string_data = NULL;
char *csum_buffer = NULL;
struct pseudo_iphdr csum_hdr;
int ready_fds, ret;
struct epoll_event
events[MAX_EVENTS];
struct epoll_event event;
signal (SIGINT,
interrupt_handler);
signal (SIGTERM,
interrupt_handler);
if (argc != 2) {
printf("%s<ip-addr>\n",
argv[0]);
exit(EXIT_FAILURE);
}
sockfd = socket(AF_INET,
SOCK_RAW,
IPPROTO_UDP);
if (sockfd < 0) {
printf("create a socket\n");
exit(0);
}
clientaddr = (struct sockaddr_in *)
malloc(sizeof(struct sockaddr_in));
if (clientaddr == NULL) {
printf("allocate memory\n");
goto end;
}
clientaddr->sin_family = AF_INET;
clientaddr->sin_port =
htons(DESTPORT);
validate_convert_addr(argv[1],
clientaddr);
memset(buffer, 0,
sizeof(buffer));
string_data = (char *)
(buffer + sizeof(struct udphdr));
strncpy(string_data,
string, strlen(string));
udp_hdr = (struct udphdr *)buffer;
udp_hdr->source = htons(SERVPORT);
udp_hdr->dest = htons(DESTPORT);
udp_hdr->len = htons(
sizeof(struct udphdr));
csum_buffer = (char *)calloc(
(sizeof(struct pseudo_iphdr) +
sizeof(struct udphdr) +
strlen(string_data)), sizeof(char));
if (csum_buffer == NULL) {
printf("allocate csum buffer\n");
goto end1;
}
csum_hdr.source_ip_addr =
inet_addr("127.0.0.1");
csum_hdr.dest_ip_addr =
inet_addr("127.0.0.1");
csum_hdr.fixed = 0;
csum_hdr.protocol = IPPROTO_UDP; /* UDP protocol */
csum_hdr.udp_len = htons(
sizeof(struct udphdr) +
strlen(string_data) + 1);
memcpy(csum_buffer,
(char *)&csum_hdr,
sizeof(struct pseudo_iphdr));
memcpy(csum_buffer +
sizeof(struct pseudo_iphdr),
buffer, (sizeof(struct udphdr) +
strlen(string_data) + 1));
udp_hdr->check = (in_cksum(
(unsigned short *) csum_buffer,
(sizeof(struct pseudo_iphdr)+
sizeof(struct udphdr) +
strlen(string_data) + 1)));
printf("checksum is %x\n",
udp_hdr->check);
free (csum_buffer);
epoll_fd = epoll_create1(0);
if (epoll_fd < 0) {
perror("Epoll creation failed");
exit(EXIT_FAILURE);
}
event.events = EPOLLIN;
event.data.fd = sockfd;
ret = epoll_ctl(epoll_fd,
EPOLL_CTL_ADD, sockfd, &event);
if (ret < 0) {
perror("Epoll_ctl failed");
exit(EXIT_FAILURE);
}
while (1) {
ret = sendto(sockfd, buffer,
(sizeof(struct udphdr)+
strlen(string_data)+1), 0,
(struct sockaddr *)clientaddr,
sizeof(struct sockaddr_in));
if (ret == -1) {
printf("send Message\n");
goto end1;
}
ready_fds = epoll_wait(epoll_fd,
events, MAX_EVENTS, -1);
if (ready_fds < 0) {
perror("Epoll wait failed");
exit(EXIT_FAILURE);
}
if (events[0].data.fd == sockfd) {
memset(recvbuffer, 0,
sizeof(recvbuffer));
ret = recvfrom(sockfd, recvbuffer,
(sizeof(struct iphdr) +
sizeof(struct udphdr)+
strlen(string_data)+1), 0,
(struct sockaddr *)clientaddr,
&length);
if (ret < 0) {
printf("recv Message\n");
goto end1;
}
udp_hdr = (struct udphdr *)
(recvbuffer +
sizeof (struct iphdr));
recv_string_data = (char *)
(recvbuffer +
sizeof (struct iphdr) +
sizeof (struct udphdr));
if (SERVPORT ==
ntohs(udp_hdr->source)) {
printf("Received :%s\n",
recv_string_data);
}
}
}
end1:
free (clientaddr);
end:
(void)close (sockfd);
return 0;
}
$ gcc -o client client.c
$ sudo ./client 127.0.0.1
Received :Hello server
Received :Hello client
Received :Hello server
Received :Hello client
Received :Hello server
Received :Hello client
Received :Hello client
Received :Hello server
Received :Hello client
Received :Hello client
Received :Hello server
^C
Default Domain:
By default, the socket is configured to work in the
AF_INET
domain, handling all types of network data.
Additional Domain Support:
We expand the socket’s capabilities to also function in the
PF_INET
domain, allowing it to operate similarly toAF_INET
.
Socket Creation:
We set up a network connection point known as a socket using
socket(PF_INET, SOCK_RAW, IPPROTO_UDP)
.
Working Scenario:
Despite the change in domain to
PF_INET
, the socket continues to operate the same way, handling general network data.
Socket API |
Learning |
---|---|
socket |
Create a new socket |
epoll |
handles a set of file descriptors with different states, such as reading, writing, and exceptions, by using the struct epoll_event structure and the associated event flags.. |
recvfrom |
It provides information about the source (sender) of the data, including the sender’s IP address and port number. |
sendto |
Send the encoded message to the specified server address and port using a socket. |
Previous topic
Current topic
Next topic
Other sockets
Other IPCs