IPV4 RAW AF INET TCP server client program with Poll system call
In this program, you are going to learn
How to create a Socket ?
How to write a data ?
How to read a data ?
Let us answer few basic questions in this socket
What does socket(AF_INET, SOCK_RAW, IPPROTO_TCP)
do?
See Answer
This call creates a raw socket in the AF_INET
address family for direct access to TCP packets.
When is it appropriate to use SOCK_RAW
sockets with TCP?
See Answer
It’s suitable for tasks like packet capturing, network monitoring, or implementing custom protocols where direct access to TCP packets is needed.
Can this socket be used for regular TCP communication?
See Answer
While technically possible, it’s not recommended for regular communication due to increased complexity and potential security risks.
How does a raw TCP socket differ from a regular TCP socket?
See Answer
A raw TCP socket provides direct access to the TCP layer, allowing for manual packet manipulation, whereas regular TCP sockets handle packet details internally.
What are some use cases for raw TCP sockets?
See Answer
Use cases include network sniffing, packet analysis, security auditing, and developing custom network protocols.
How can I capture and analyze TCP packets using raw sockets?
See Answer
You can use the raw socket to capture TCP packets and analyze them using packet analysis tools like Wireshark.
Is error checking needed after creating the socket?
See Answer
Yes, checking for errors ensures that the socket is created successfully before proceeding with further operations.
Why is it important to check the return value of read() and write() in socket programming?
See Answer
It detects issues such as network errors or closed connections.
What is the purpose of the poll system call?
See Answer
To block and wait for activity on one or more file descriptors.
How does poll differ from poll in terms of usability?
See Answer
poll is more efficient than poll for monitoring multiple file descriptors.
What types of file descriptors can be monitored using poll?
See Answer
sockets, files, timerfd, socketpair, message_queue, Namedpipes and shared_memory.
How does poll handle a set of file descriptors with different states (e.g., reading, writing, exception)?
See Answer
It uses different structures for each state in the pollfd array.
How do you handle errors when using the poll system call?
See Answer
Check the return value for -1 to detect errors, Use perror to print error messages.
How does poll handle a set of file descriptors with different states (e.g., reading, writing, exception)?
See Answer
- Array of pollfd Structures:
Before calling poll, you need to create an array of pollfd structures, where each structure represents a file descriptor and its associated events.
struct pollfd fds[NUM_FDS];
NUM_FDS is the number of file descriptors you want to monitor.
- Initialize pollfd Structures:
For each file descriptor you want to monitor, initialize the corresponding pollfd structure with the following information:
fd: The file descriptor to monitor. events: The events of interest (e.g., POLLIN for readability, POLLOUT for writability). revents: Initially set to zero. After the poll call, this field is updated to indicate the events that occurred.
fds[0].fd = fd1;
fds[0].events = POLLIN;
fds[0].revents = 0;
fds[1].fd = fd2;
fds[1].events = POLLIN;
fds[1].revents = 0;
- Call poll:
After initializing the pollfd array, call the poll function, providing the array, the number of file descriptors, and a timeout
int ready_fds = poll(fds, NUM_FDS, timeout_ms);
ready_fds will contain the number of file descriptors that are ready.
How does poll Checking Ready File Descriptors?
See Answer
After the poll call, loop through the pollfd array and check the revents field for each file descriptor to determine which events occurred.
for (int i = 0; i < NUM_FDS; ++i) {
if (fds[i].revents & POLLIN) {
// File descriptor i is ready for reading
}
if (fds[i].revents & POLLOUT) {
// File descriptor i is ready for writing
}
// Check other events if needed (e.g., POLLERR, POLLHUP)
}
What does it mean if poll 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
Bind Socket
Connect Socket
Poll
Write data_packet
Read data_packet
Close socket
socket()
is used to create a new socket. For example,
sock_fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
bind()
is used to associate the socket with a specific address and port. For example,
ret = bind(sock_fd, (struct sockaddr*)servaddr, sizeof(struct sockaddr_in));
connect()
is used in network programming to establish a connection from a client to a server. For example,
ret = connect(sock_fd, (struct sockaddr*)client_addr, sizeof(struct sockaddr_in));
poll()
is used for monitoring multiple file descriptors to see if I/O is possible on any of them.
ret = poll(fds, 1, 1000);
read
system call in C is commonly used to read data from a file descriptor, such as a socket.
ret = read(sock_fd, recvbuffer, sizeof(recvbuffer));
write
system call in C is used to write data to a file descriptor, such as a socket.
ret = write(sock_fd, buffer, sizeof(buffer));
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 <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <errno.h>
#include <linux/ip.h>
#include <netinet/tcp.h>
#include <poll.h>
#define PORT 50000
#define PORT_CLIENT 50001
struct sockaddr_in
*servaddr = NULL,
*client_addr = NULL;
int sock_fd;
struct pseudo_iphdr {
unsigned int source_ip_addr;
unsigned int dest_ip_addr;
unsigned char fixed;
unsigned char protocol;
unsigned short tcp_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(client_addr);
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[])
{
char buffer[1024] =
{0};
unsigned char recvbuffer[1024] =
{0};
int length, ret;
char *string =
"Hello client";
struct tcphdr *tcp_hdr = NULL;
char *string_data = NULL;
char *recv_string_data = NULL;
char *csum_buffer = NULL;
struct pseudo_iphdr
csum_hdr;
struct pollfd fds[1];
if (argc != 2) {
printf("%s<ip-addr>\n",
argv[0]);
exit(EXIT_FAILURE);
}
signal (SIGINT,
interrupt_handler);
signal (SIGTERM,
interrupt_handler);
sock_fd = socket(AF_INET,
SOCK_RAW,
IPPROTO_TCP);
if(0 > sock_fd) {
printf("unable to create\n");
exit(0);
}
servaddr = (struct sockaddr_in *)malloc(
sizeof(struct sockaddr_in));
if (servaddr == NULL) {
printf("could not allocate memory\n");
goto end;
}
servaddr->sin_family = AF_INET;
servaddr->sin_port = PORT;
validate_convert_addr(argv[1],
servaddr);
ret = bind(sock_fd,
(struct sockaddr *)servaddr,
sizeof(struct sockaddr_in));
if (ret < 0) {
printf("bind\n");
goto end1;
}
client_addr = (struct sockaddr_in *)malloc(
sizeof(struct sockaddr_in));
if (client_addr == NULL) {
printf("allocation memory\n");
goto end2;
}
client_addr->sin_family = AF_INET;
client_addr->sin_port =
PORT_CLIENT;
validate_convert_addr(argv[1],
client_addr);
ret = connect(sock_fd,
(struct sockaddr *)client_addr,
sizeof(struct sockaddr_in));
if (ret != 0) {
printf("error %d", errno);
printf("connect returned error\n");
goto end2;
}
string_data = (char *)
(buffer + sizeof(struct tcphdr));
strncpy(string_data, string,
strlen(string));
tcp_hdr = (struct tcphdr *)buffer;
tcp_hdr->source = htons(PORT);
tcp_hdr->dest =
htons(PORT_CLIENT);
tcp_hdr->ack_seq = 0x0;
tcp_hdr->doff = 5;
tcp_hdr->syn = 1;
tcp_hdr->window = htons(200);
csum_buffer = (char *)calloc((
sizeof(struct pseudo_iphdr) +
sizeof(struct tcphdr) +
strlen(string_data)),
sizeof(char));
if (csum_buffer == NULL) {
printf("allocate csum buffer\n");
goto end1;
}
csum_hdr.source_ip_addr =
inet_addr("192.168.1.11");
csum_hdr.dest_ip_addr =
inet_addr("192.168.1.14");
csum_hdr.fixed = 0;
csum_hdr.protocol =
IPPROTO_TCP;
csum_hdr.tcp_len =
htons(sizeof(struct tcphdr) +
strlen(string_data) + 1);
memcpy(csum_buffer, (char *)&csum_hdr,
sizeof(struct pseudo_iphdr));
memcpy(csum_buffer +
sizeof(struct pseudo_iphdr), buffer,
(sizeof(struct tcphdr) +
strlen(string_data) + 1));
tcp_hdr->check = (in_cksum(
(unsigned short *) csum_buffer,
(sizeof(struct pseudo_iphdr)+
sizeof(struct tcphdr) + strlen(string_data) + 1)));
printf("checksum is %x", tcp_hdr->check);
free (csum_buffer);
memset(fds, 0, sizeof(fds));
fds[0].fd = sock_fd;
fds[0].events = POLLIN;
while (1) {
ret = poll(fds, 1, 1000);
if (ret == -1) {
perror("poll\n");
break;
}
if (fds[0].revents & POLLIN) {
memset(recvbuffer, 0,
sizeof(recvbuffer));
ret = read(sock_fd, recvbuffer,
sizeof(recvbuffer));
if (ret == -1) {
perror("read error");
break;
}
tcp_hdr = (struct tcphdr *)
(recvbuffer +
sizeof (struct iphdr));
recv_string_data = (char *)
(recvbuffer +
sizeof (struct iphdr) +
sizeof (struct tcphdr));
if (PORT == ntohs(
tcp_hdr->dest)) {
printf("Received : %s\n",
recv_string_data);
}
ret = write(sock_fd, buffer,
sizeof(buffer));
if (ret == -1) {
perror("write error");
break;
}
}
}
end2:
free(client_addr);
end1:
free(servaddr);
end:
(void)close(sock_fd);
return 0;
}
$ gcc -o server server.c
$ sudo ./server 127.0.0.1
IP Address: 127.0.0.1
IP Address: 127.0.0.1
checksum is c945
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
Received : Hello server
^C
There are many functions used in socket. We can classify those functions based on functionalities.
Create Socket
Bind Socket
Connect Socket
Poll
Write data_packet
Read data_packet
Close socket
socket
is used to create a new socket. For example,
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
bind()
is used to associate the socket with a specific address and port. For example,
ret = bind(sockfd, (struct sockaddr*)clientaddr, sizeof(struct sockaddr_in));
connect()
is used in network programming to establish a connection from a client to a server. For example,
ret = connect(sockfd, (struct sockaddr*)serveraddr, sizeof(struct sockaddr_in));
poll()
is used for monitoring multiple file descriptors to see if I/O is possible on any of them.
ret = poll(fds, 2, -1);
read
system call in C is commonly used to read data from a file descriptor, such as a socket.
ret = read(sockfd, recvbuffer, sizeof(recvbuffer));
write
system call in C is used to write data to a file descriptor, such as a socket.
ret = write(sockfd, buffer, sizeof(buffer));
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 <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <errno.h>
#include <netinet/tcp.h>
#include <linux/ip.h>
#include <poll.h>
#define PORT 50001
#define SERVER_PORT 50000
struct sockaddr_in
*serveraddr = NULL,
*clientaddr;
int sockfd;
struct pseudo_iphdr {
unsigned int source_ip_addr;
unsigned int dest_ip_addr;
unsigned char fixed;
unsigned char protocol;
unsigned short tcp_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)
{
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[])
{
char buffer[1024] =
{0};
unsigned char recvbuffer[1024] =
{0};
int length, ret;
char *string =
"Hello server";
struct tcphdr *tcp_hdr = NULL;
char *string_data = NULL;
char *recv_string_data = NULL;
char *csum_buffer = NULL;
struct pseudo_iphdr csum_hdr;
int error;
struct pollfd fds[2];
if (argc != 2) {
printf("%s<ip-addr>\n",
argv[0]);
exit(EXIT_FAILURE);
}
signal (SIGINT,
interrupt_handler);
signal (SIGTERM,
interrupt_handler);
sockfd = socket(AF_INET,
SOCK_RAW,
IPPROTO_TCP);
if(0 > sockfd) {
printf("create 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 = PORT;
validate_convert_addr(argv[1],
clientaddr);
ret = bind(sockfd,
(struct sockaddr *)clientaddr,
sizeof(struct sockaddr_in));
if (ret < 0) {
printf(" bind\n");
goto end1;
}
serveraddr = (struct sockaddr_in *)malloc(
sizeof(struct sockaddr_in));
if (serveraddr == NULL) {
printf("allocate memory\n");
goto end2;
}
serveraddr->sin_family = AF_INET;
serveraddr->sin_port = SERVER_PORT;
validate_convert_addr(argv[1],
serveraddr);
ret = connect(sockfd,
(struct sockaddr *)serveraddr,
sizeof(struct sockaddr_in));
if (ret != 0) {
printf("error %d", errno);
printf("connect returned error\n");
goto end2;
}
string_data = (char *)
(buffer + sizeof(struct tcphdr));
strncpy(string_data, string,
strlen(string));
tcp_hdr = (struct tcphdr *)buffer;
tcp_hdr->source = htons(PORT);
tcp_hdr->dest = htons(SERVER_PORT);
tcp_hdr->ack_seq = 0x0;
tcp_hdr->doff = 5;
tcp_hdr->syn = 1;
tcp_hdr->window = htons(200);
csum_buffer = (char *)calloc(
(sizeof(struct pseudo_iphdr) +
sizeof(struct tcphdr) +
strlen(string_data)), sizeof(char));
if (csum_buffer == NULL) {
printf("allocate csum buffer\n");
goto end1;
}
csum_hdr.source_ip_addr =
inet_addr("192.168.1.14");
csum_hdr.dest_ip_addr =
inet_addr("192.168.1.11");
csum_hdr.fixed = 0;
csum_hdr.protocol =
IPPROTO_TCP;
csum_hdr.tcp_len =
htons(sizeof(struct tcphdr) +
strlen(string_data) + 1);
memcpy(csum_buffer,
(char *)&csum_hdr,
sizeof(struct pseudo_iphdr));
memcpy(csum_buffer +
sizeof(struct pseudo_iphdr),
buffer, (sizeof(struct tcphdr) +
strlen(string_data) + 1));
tcp_hdr->check = (in_cksum(
(unsigned short *) csum_buffer,
(sizeof(struct pseudo_iphdr)+
sizeof(struct tcphdr) +
strlen(string_data) + 1)));
printf("checksum is %x",
tcp_hdr->check);
free (csum_buffer);
memset(fds, 0, sizeof(fds));
fds[0].fd = sockfd;
fds[0].events = POLLIN;
while (1) {
ret = write(sockfd,
buffer, sizeof(buffer));
if (ret < 0) {
perror("read error");
break;
}
ret = poll(fds, 2, -1);
if (ret < 0) {
perror("poll\n");
break;
}
if (fds[0].revents & POLLIN) {
memset(recvbuffer, 0,
sizeof(recvbuffer));
ret = read(sockfd,
recvbuffer, sizeof(recvbuffer));
if (ret < 0) {
perror("read error");
break;
}
tcp_hdr = (struct tcphdr *)
(recvbuffer + sizeof (struct iphdr));
recv_string_data = (char *)
(recvbuffer + sizeof (struct iphdr) +
sizeof (struct tcphdr));
if (PORT == ntohs(tcp_hdr->dest)) {
printf("Received : %s\n",
recv_string_data);
}
}
}
end2:
free(serveraddr);
end1:
free(clientaddr);
end:
(void)close(sockfd);
return 0;
}
$ gcc -o client client.c
$ sudo ./client 127.0.0.1
IP Address: 127.0.0.1
IP Address: 127.0.0.1
checksum is c135
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
Received : Hello client
^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_TCP)
.
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 |
poll |
Monitor multiple file descriptors (usually sockets) for read, write, or error conditions. |
write |
used to write data to a file descriptor, such as a socket. |
read |
used to read data from a file descriptor, such as a socket. |
previous topic
current topic
Next topic
Other sockets
Other IPCs