Basic example raw af inet tcp server and client

  • In this program, you are going to learn

  • How to create a Socket ?

  • How to bind a socket ?

  • How to send a data ?

  • How to recv a data ?

Let us answer few basic questions in this socket

What does socket(AF_INET, SOCK_RAW, IPPROTO_TCP) do?

When is it appropriate to use SOCK_RAW sockets with TCP?

Can this socket be used for regular TCP communication?

How does a raw TCP socket differ from a regular TCP socket?

What are some use cases for raw TCP sockets?

How can I capture and analyze TCP packets using raw sockets?

Is error checking needed after creating the socket?

Why is it important to check the return value of sendto() and recvfrom() in socket programming?

https://www.plantuml.com/plantuml/svg/NOyz2uCm48Rt_8fqAKd9q5aNHLgGYegrT0mnEQbKZIJHeR--MWlzM0wUktiVU0FhX75ZrwADkq47s0v2GYigz3eWpsfv1qV28u_JGydmEOjEl0Yl3CTvNcHbniiefpxoggPNn8APmF0rn32npepIuOM5KcP7j--FXHYspGDqJRvsT54Pa5DjTFUlgyQwXaziHShmdk7qaYJhN0HaqesYijKMVXt-N4iFA81UpPsV
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Bind Socket

    • Recvfrom data_packet

    • Sendto data_packet

    • Close socket

  • socket() is used to create a new socket. For example,

server_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
  • bind() is used to associate the socket with a specific address and port. For example,

ret = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • 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,

len  = recvfrom(server_socket, buffer, sizeof(buffer), 0, NULL, NULL);
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(server_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <ctype.h>

#define PORT 8080
#define BUFFER_SIZE 1024

void recv_data(
const char *packet, 
size_t length) 
{
    int header_size, i;
    char c;

    header_size = sizeof(struct iphdr) + 
    sizeof(struct tcphdr);
    
    printf("Receivedpacket:");

    for (i = header_size; i < length; ++i) {
        c = packet[i];
        if (isprint(c) || c == '\n' 
	|| c == '\r') {
            printf("%c", c);
	}
    }
    printf("\n");
}

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[]) 
{
    int server_socket;
    int len, ret;
    struct sockaddr_in 
    server_addr;
    char buffer[BUFFER_SIZE];

    if (argc != 2) {
        printf("%s<ip-addr>\n",
        argv[0]);
        exit(EXIT_FAILURE);
    }

    server_socket = socket(AF_INET, 
		    SOCK_RAW, 
		    IPPROTO_TCP);

    if (server_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    validate_convert_addr(argv[1],
    &server_addr);

    ret = bind(server_socket, 
    (struct sockaddr*)&server_addr, 
    sizeof(server_addr)); 
    
    if (ret < 0) {
        perror("Bind failed");
        (void)close(server_socket);
        exit(EXIT_FAILURE);
    }

    printf("Serverlisten\n");

    len = recv(server_socket, 
    buffer, sizeof(buffer), 0);

    if (len < 0) {
        perror("Receive failed");
        (void)close(server_socket);
        exit(EXIT_FAILURE);
    }

    recv_data(buffer, len);

    (void)close(server_socket);

    return 0;
}

$ gcc -o server server.c

$ sudo ./server 127.0.0.1

IP Address: 127.0.0.1
Serverlisten
Receivedpacket:_Hello from client!
https://www.plantuml.com/plantuml/svg/LO-n2i8m48RtFiMvIA8P13TTAaL115kqu1ZIv8h1s9Jawk3JcoeYZlT_Tp_VvP5KeE7kiWbTyOuGUwNHgIPxWsmLlRuXiSrExe_RMi2vB0xojBa8s5VLgQnBMHSLNwT5x0nvfft5ZkJdJ40pj2q6cCDIGBHFz2sB50PDOFkh2JoH_vZqDtVO2LW8-9AnKXaJPdmQCJmmo77wrVuoFlgmXxU6Q-SZ_aib6CdtMPw4q-Cl
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Sendto data_packet

    • Close socket

  • socket is used to create a new socket. For example,

client_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
  • sendto is used to send the encoded message to the specified server address and port using a socket. For example,

ret = sendto(client_socket, buffer + 3, sizeof(struct iphdr) + sizeof(struct tcphdr) + len, 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(client_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>

#define SERVER_IP "127.0.0.1"
#define PORT 8080
#define BUFFER_SIZE 1024

void craft_tcp_packet(
char *buffer, 
const char *data, 
size_t data_len) 
{
    struct iphdr *ip_header;
    struct tcphdr *tcp_header;
   
    ip_header = (struct iphdr *)buffer;
    ip_header->ihl = 5;                   
    ip_header->version = 4;               
    ip_header->tos = 0;                   
    ip_header->tot_len = sizeof(struct iphdr) + 
    sizeof(struct tcphdr) + data_len;
    ip_header->id = htons(54321);         
    ip_header->frag_off = 0;              
    ip_header->ttl = 255;                 
    ip_header->protocol = IPPROTO_TCP;    
    ip_header->check = 0;                 
    ip_header->saddr = INADDR_ANY;        
    ip_header->daddr = INADDR_ANY;     

    tcp_header = (struct tcphdr *)
    (buffer + sizeof(struct iphdr));
    tcp_header->source = htons(12345);    
    tcp_header->dest = htons(PORT);       
    tcp_header->seq = 0;                  
    tcp_header->ack_seq = 0;              
    tcp_header->doff = 5;                 
    tcp_header->fin = 0;                
    tcp_header->syn = 0;                  
    tcp_header->rst = 0;                  
    tcp_header->psh = 1;                  
    tcp_header->ack = 0;                  
    tcp_header->urg = 0;                  
    tcp_header->window = htons(5840);     
    tcp_header->check = 0;                
    tcp_header->urg_ptr = 0;              

    memcpy(buffer + 
    sizeof(struct iphdr) + 
    sizeof(struct tcphdr), data, 
    data_len);
}

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[]) 
{
    int client_socket;
    int i, len, ret;
    struct sockaddr_in 
    server_addr;
    char buffer[BUFFER_SIZE];
    const char *message = 
    "Hello from client!";

    if (argc != 2) {
        printf("%s<ip-addr>\n",
        argv[0]);
        exit(EXIT_FAILURE);
    }

    client_socket = socket(AF_INET, 
		    SOCK_RAW, 
		    IPPROTO_TCP);

    if (client_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    validate_convert_addr(argv[1],
    &server_addr);

    len = strlen(message);

    craft_tcp_packet(buffer, 
    message, len);

    strcpy(buffer + 3, message);    
    
    ret = sendto(client_socket, buffer + 3, 
    sizeof(struct iphdr) + 
    sizeof(struct tcphdr) + len,
    0, (struct sockaddr *)&server_addr, 
    sizeof(server_addr));

    if (ret < 0) {
        perror("Send failed");
        (void)close(client_socket);
        exit(EXIT_FAILURE);
    }

    printf("Sentpacket:%s\n", message);

    (void)close(client_socket);

    return 0;
}

$ gcc -o client client.c

$ sudo ./client 127.0.0.1

IP Address: 127.0.0.1
Sentpacket:Hello from client!
https://www.plantuml.com/plantuml/svg/NL31QiCm3BtxAxJBi5SVUausQ2ZPA6kRq6JiQ19ReMP9NImdO_lw9KrXwouIx-dfFQ4LXSg7lclPNJXYXq3dIcDRrUmoO14v_O619yzgiqzB2KMsVbM7v5t29iyFMPcfSfsBc4MrFHbEw0VqQbwIm2duNWUOS6MCVn3tLyM4993zHjVmFvoOh2mymJ9cdqVR8l1hi_08-xUTsgL5aRoaXH1W2VWNac2HHpqqtdN_3wZxfi7Ve1aA2KivUcstSvqY5miRCpoPInYB-E2i4RfrXBUMevQ2ExFLg1s_zWC=
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Bind Socket

    • Recvfrom data_packet

    • Close socket

  • socket() is used to create a new socket. For example,

server_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
  • bind() is used to associate the socket with a specific address and port. For example,

ret = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • 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,

len  = recvfrom(server_socket, buffer, sizeof(buffer), 0, NULL, NULL);
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(server_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <ctype.h>

#define PORT 8081
#define BUFFER_SIZE 1024
#define NUM_MESSAGES 10

void recv_data(
const char *packet, 
size_t length) 
{
    int header_size, i;
    char c;

    header_size = sizeof(struct iphdr) + 
    sizeof(struct tcphdr);

    printf("Received: ");
    for (i = header_size; i < length; ++i) {
        c = packet[i];
        if (isprint(c) || c == '\n' || c == '\r') {
            printf("%c", c);
	}
    }
    printf("\n");
}

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[]) 
{
    int server_socket;
    int i, ret, len;
    struct sockaddr_in 
    server_addr;
    char buffer[BUFFER_SIZE];

    if (argc != 2) {
	printf("%s<ip-addr>",
	argv[0]);
	exit(EXIT_FAILURE);
    }

    server_socket = socket(AF_INET, 
		    SOCK_RAW, 
		    IPPROTO_TCP);

    if (server_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    validate_convert_addr(argv[1], 
    &server_addr);

    ret = bind(server_socket, 
    (struct sockaddr*)&server_addr, 
    sizeof(server_addr)); 
 
    if (ret < 0) {
        perror("Bind failed");
        (void)close(server_socket);
        exit(EXIT_FAILURE);
    }

    printf("Server listening\n");

    i = 0;
    while (i < NUM_MESSAGES) {
        len = recv(server_socket, 
	buffer, sizeof(buffer), 0);

        if (len < 0) {
            perror("Receive failed");
	    break;
        }

        recv_data(buffer, len);
	++i;
    }
    
    (void)close(server_socket);

    return 0;
}

$ gcc -o server server.c

$ sudo ./server 127.0.0.1

IP Address: 127.0.0.1
Server listening
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
Received: _Hello from client!
https://www.plantuml.com/plantuml/svg/LL11QiCm4Bph5TjBaMeT0htPBSG4fuIIsCGkFGf7McCHnJAIdDA-ldBQ479QTcQOdTcb3wqBqycGXz3Z2S6FhKJJ7iY58ActyeY1vcknsHKDXxfSlOjz_ibXKrNxiYb5iwfOHb8Dhx38o5Ul3GBz7nfUOFUn5TkYhlEtecOCj0VwZPv5QnnKi5GQZKCGVuSu7AQkGmS9F7Fm-WTjHtrmamoWnruv5fbxECWhRd3WiE1mPMRBLYdtn1uzkZCwCMytsnl6vWP9eZCICrsoavIUhLPC6klnFcFK-c17iepQ-BbV
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Sendto data_packet

    • Close socket

  • socket is used to create a new socket. For example,

client_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
  • sendto is used to send the encoded message to the specified server address and port using a socket. For example,

ret = sendto(client_socket, buffer + 3, sizeof(struct iphdr) + sizeof(struct tcphdr) + len, 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(server_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>

#define BUFFER_SIZE 1024
#define NUM_MESSAGES 10
#define PORT 8081

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 craft_tcp_packet(
char *buffer, 
const char *data, 
size_t data_len) 
{
    struct iphdr *ip_header;
    struct tcphdr *tcp_header;
    int i;

    ip_header = (struct iphdr *)buffer;
    ip_header->ihl = 5;                   
    ip_header->version = 4;               
    ip_header->tos = 0;                   
    ip_header->tot_len = sizeof(struct iphdr) + 
    sizeof(struct tcphdr) 
    + data_len; 
    ip_header->id = htons(54321);         
    ip_header->frag_off = 0;              
    ip_header->ttl = 255;                 
    ip_header->protocol = IPPROTO_TCP;    
    ip_header->check = 0;                
    ip_header->saddr = INADDR_ANY;        
    ip_header->daddr = INADDR_ANY;  

    tcp_header = (struct tcphdr *)
    (buffer + sizeof(struct iphdr));
    tcp_header->source = htons(12345);    
    tcp_header->dest = htons(PORT) ;      
    tcp_header->seq = 0;                  
    tcp_header->ack_seq = 0;             
    tcp_header->doff = 5;                 
    tcp_header->fin = 0;                  
    tcp_header->syn = 0;                  
    tcp_header->rst = 0;                  
    tcp_header->psh = 1;                  
    tcp_header->ack = 0;                  
    tcp_header->urg = 0;                  
    tcp_header->window = htons(5840);     
    tcp_header->check = 0;                
    tcp_header->urg_ptr = 0;              
    
    memcpy(buffer + sizeof(struct iphdr) + 
    sizeof(struct tcphdr), data, data_len);
}

int main(int argc, char *argv[]) 
{
    int client_socket;
    int ret, i;
    int len;
    struct sockaddr_in 
    server_addr;
    char buffer[BUFFER_SIZE];
    const char *message = 
    "Hello from client!";

    if (argc != 2) {
	printf("%s<ip-addr>\n",
	argv[0]);
	exit(EXIT_FAILURE);
    }

    client_socket = socket(AF_INET, 
		    SOCK_RAW, 
		    IPPROTO_TCP);

    if (client_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    validate_convert_addr(argv[1],
    &server_addr);

    len = strlen(message);

    craft_tcp_packet(buffer, 
    message, len);

    strcpy(buffer + 3, message);   

    i = 0;
    while (i < NUM_MESSAGES) { 
   
    ret = sendto(client_socket, 
    buffer + 3, 
    sizeof(struct iphdr) + 
    sizeof(struct tcphdr) + len,
    0, (struct sockaddr *)&server_addr, 
    sizeof(server_addr));

    if (ret < 0) {
        perror("Send failed");
        (void)close(client_socket);
        exit(EXIT_FAILURE);
    }

    printf("Sentpacket: %s\n", 
    message);
    ++i;
    }

    (void)close(client_socket);

    return 0;
}

$ gcc -o client client.c

$ sudo ./client 127.0.0.1

IP Address: 127.0.0.1
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!
Sentpacket: Hello from client!

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 to AF_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

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.