af unix tcp server client program with Select system call

  • In this program, you are going to learn

  • How to create a Socket ?

  • How to bind a socket ?

  • How to listen a socket ?

  • How to connect a socket ?

  • How to accept a socket ?

  • How to send a data ?

  • How to recv a data ?

Let us answer few basic questions in this socket

What does AF_UNIX represent in the socket call?

Why use SOCK_STREAM as the socket type?

What does the third parameter (0) indicate in socket(AF_UNIX, SOCK_STREAM, 0)?

How can I set up a server and client using AF_UNIX sockets?

How should errors in the socket call be handled?

What is the role of the file system path in AF_UNIX sockets?

What is the role of the file system path in AF_UNIX sockets?

Why might bind() or listen() fail in socket programming?

How should you handle errors when using accept() in socket programming?

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

What is the purpose of the select system call in network programming?

How does select help in handling multiple sockets efficiently?

What types of file descriptors can be monitored using select?

What is the significance of the timeout parameter in the select function?

How do you handle errors when using the select system call?

How does select handle a set of file descriptors with different states (e.g., reading, writing, exception)?

How does select Checking Ready File Descriptors?

What does it mean if select returns 0?

https://www.plantuml.com/plantuml/svg/TP9DQm8n48Rl-HNJIqdg5kgXboq5nIf8hOAhK7fPOZB1qBWhcMW_VdqJTz4jj3bCc8_ddV2I0GNfms7ds5NOuWw1zbAXanjsQh2SQlMEWGydvNe-VSsWM8oUosAr70zVChWJ3opVs4fpGdz4NngT0QVW3of08gNM_aPSjzsKPK3s6sl3EpMHP9obW5LNw3wLbRDOXPZ38qYbS1-w8_FrRDR4EFknjGw1doxU5m8i0Vz24YoVF9Llu-M2NtkKEfAKf6En6A_uUKC6lzg43bNWHk_a9_IWtsbt5v_NMmCyIawBVqK5H8-hzasGJkvH7Rl3cuCnU36fIGNSflN9xOOYZ9R_HGNleeSjrH3eA9fIrO95o9eKMwD6g-Mifw8x_5XRBPIh2I-g4QLGxzaW0l5__00=
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Bind Socket

    • Listen Socket

    • Accept Socket

    • Select

    • Recv data_packet

    • Send data_packet

    • Close socket

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

tcp_server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
  • bind() is used to associate the socket with a specific address and port. For example,

ret = bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • listen() is used to set up a socket to accept incoming connections. For example,

ret = listen(server_fd, 5);
  • accept() is used in network programming on the server side to accept a connection request from a client. For example,

client_fd = accept(server_fd, NULL, NULL);
  • select() is used in network programming to monitor multiple file descriptors (usually sockets) for read, write, or error conditions. For example,

ret = select(fdmax + 1, &read_fds, NULL, NULL, NULL);
  • recv is used in network programming to receive data from a connected socket. For example,

len = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
  • send is used in network programming to send data over a connected socket. For example,

ret = send(client_fd, buffer, strlen(buffer), 0);
  • close is used to close the socket To free up system resources associated with the socket. For example,

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>

#define SOCKET_PATH "/tmp/my_socket"

int server_fd, client_fd;

static void sigint_handler(int signo)
{
  unlink(SOCKET_PATH);
  (void)close(server_fd);
  (void)close(client_fd);
  sleep(2);
  printf("Caught sigINT!\n");
  exit(EXIT_SUCCESS);
}

void register_signal_handler(
int signum,
void (*handler)(int))
{
  if (signal(signum, handler) ==
  SIG_ERR) {
     printf("Cannot handle signal\n");
     exit(EXIT_FAILURE);
  }
}

void recv_send(char *buffer)
{
  int len, ret;

  memset(buffer, 0, sizeof(buffer));
  len = recv(client_fd, buffer,
  sizeof(buffer) - 1, 0);

  if (len > 0) {
    buffer[len] = '\0';
    printf("Received: %s\n",
    buffer);

    memset(buffer, 0,
    sizeof(buffer));
    strncpy(buffer, "HELLO",
    strlen("HELLO") + 1);
    buffer[strlen(buffer) + 1] = '\0';
    printf("Sentbuffer = %s\n",
    buffer);

    ret = send(client_fd, buffer,
    strlen(buffer), 0);

    if (ret < 0) {
       perror("send error\n");
       (void)close(client_fd);
       (void)close(server_fd);
       exit(EXIT_FAILURE);
    }

   } else if (len < 0) {
      perror("recv");
      (void)close(client_fd);
      (void)close(server_fd);
      exit(EXIT_FAILURE);
    }
}

int main(void) 
{
  int fdmax = 0;
  int ret;
  struct sockaddr_un 
  server_addr, 
  client_addr;
  char buffer[1024];
  fd_set read_fds;

  register_signal_handler(SIGINT,
  sigint_handler);

  memset(&server_addr, 0, 
  sizeof(struct sockaddr_un));
  server_addr.sun_family = AF_UNIX;
  strncpy(server_addr.sun_path, 
  SOCKET_PATH, 
  sizeof(server_addr.sun_path) - 1);
  unlink(SOCKET_PATH);

  server_fd = socket(AF_UNIX, 
              SOCK_STREAM, 0);
 
  if (server_fd < 0) {
    perror("socket");
    return -1;
  }

  ret = bind(server_fd, 
  (struct sockaddr*)&server_addr, 
  sizeof(struct sockaddr_un));
  
  if (ret < 0) {
    perror("bind");
    (void)close(server_fd);
    return -2;
  }

  ret = listen(server_fd, 5);
  
  if (ret < 0) {
    perror("listen");
    (void)close(server_fd);
    return -3;
  }

  printf("Server listening\n");
 
  client_fd = accept(server_fd, 
  NULL, NULL);

  if (client_fd == -1) {
     perror("accept");
     (void)close(server_fd);
     return -4;
  }
  
  printf("connection accepted = %d\n", 
  client_fd);

  fdmax = client_fd;
  
  while (1) {
    FD_ZERO(&read_fds);
    FD_SET(client_fd, &read_fds);

    ret = select(fdmax + 1, 
    &read_fds, NULL, NULL, NULL);
    
    if (ret < 0) {
      perror("select");
      break;
    }
    
    if(FD_ISSET(client_fd, 
      &read_fds)) {
      recv_send(buffer);
    }
  }
       
  (void)close(client_fd);
  (void)close(server_fd);
  
  return 0;
}

 1$ gcc -o server server.c
 2
 3$ sudo ./server
 4
 5Server listening
 6connection accepted = 4
 7Received: HI
 8Sentbuffer = HELLO
 9Received: HI
10Sentbuffer = HELLO
11Received: HI
12Sentbuffer = HELLO
13Received: HI
14Sentbuffer = HELLO
15Received: HI
16Sentbuffer = HELLO
17Received: HI
18Sentbuffer = HELLO
19Received: HI
20Sentbuffer = HELLO
21Received: HI
22Sentbuffer = HELLO
23Received: HI
24Sentbuffer = HELLO
25Received: HI
26^CCaught sigINT!
https://www.plantuml.com/plantuml/svg/TL71QiCm3BtdAxHBiTSCrcjtQUbIACjQQ58OlOJKKQYPQnVBoTY-VaeRM3es7sHawJtfFSyeb3uq9nFTXIEU4EXSAZJb8ReKeYavzOv1p9V5RhrwYo7RB5wABDycyzSO7kLJD5NEMbH1AAFHXgAkOX0KVAC2TE2ogloz717w5dtHPJ6G_a9N_-ug6YkPyEEe3OAuN68Y9MW2yOaaUHcqrN3EeQbhxFY2DsZ5DPNzNildOfziDsBaiQoudVh7BCc773TbGdCZ1SOm6RJ4iDwbwJ0oIDSWc7QL_KiiWRsrlGZWC_MesZ-5N8tfXS13DxqJWuRO4kjan0xekekzJOjycuuLUoDQfokfZ2FyOMOe1NUEPWpWJ_u6
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Connect Socket

    • Select

    • Recv data_packet

    • Send data_packet

    • close socket

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

client_fd = socket(AF_UNIX, SOCK_STREAM, 0);
  • connect is used in network programming to establish a connection from a client to a server. For example,

cli_connect = connect(client_fd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr_un));
  • select is used in network programming to monitor multiple file descriptors (usually sockets) for read, write, or error conditions. For example,

ret = select(client_fd + 1, &read_fds, NULL, NULL, NULL);
  • send is used in network programming to send data over a connected socket. For example,

ret = send(client_fd, buffer, strlen(buffer), 0);
  • recv is used in network programming to receive data from a connected socket. For example,

len = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
  • close is used to close the socket To free up system resources associated with the socket. For example,

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

  1#include <stdio.h>
  2#include <stdlib.h>
  3#include <string.h>
  4#include <unistd.h>
  5#include <sys/socket.h>
  6#include <sys/un.h>
  7#include <signal.h>
  8
  9#define SOCKET_PATH "/tmp/my_socket"
 10
 11int client_fd;
 12
 13static void sigint_handler(int signo)
 14{
 15  unlink(SOCKET_PATH);
 16  (void)close(client_fd);
 17  sleep(2);
 18  (void)printf("Caught sigINT!\n");
 19  exit(EXIT_SUCCESS);
 20}
 21
 22void register_signal_handler(
 23int signum,
 24void (*handler)(int))
 25{
 26  if (signal(signum, handler) ==
 27  SIG_ERR) {
 28     printf("Cannot handle signal\n");
 29     exit(EXIT_FAILURE);
 30  }
 31}
 32
 33void recv_data(char *buffer)
 34{
 35  int ret, len;
 36
 37  len = recv(client_fd, buffer,
 38  sizeof(buffer) - 1, 0);
 39
 40  if (len > 0) {
 41    buffer[len] = '\0';
 42    (void)printf("Received: %s\n",
 43    buffer);
 44    
 45  } else if (len == 0) {
 46     printf("Connection closed\n");
 47     exit(EXIT_FAILURE);
 48   }
 49}
 50
 51void send_data(char *buffer)
 52{
 53  int ret;
 54  
 55  memset(buffer, 0, sizeof(buffer));
 56
 57  strncpy(buffer, "HI",
 58  strlen("HI") + 1);
 59  buffer[strlen(buffer) + 1] = '\0';
 60
 61  ret = send(client_fd, buffer,
 62  strlen(buffer), 0);
 63
 64  if (ret < 0) {
 65    perror("send error\n");
 66    (void)close(client_fd);
 67    exit(EXIT_FAILURE);
 68  }
 69  printf("sentbuffer = %s\n", 
 70  buffer);
 71}
 72
 73int main(void) 
 74{
 75  int cli_connect;
 76  int ret;
 77  struct sockaddr_un 
 78  server_addr;
 79  char buffer[1024];
 80  fd_set read_fds;
 81
 82  register_signal_handler(SIGINT,
 83  sigint_handler);
 84
 85  memset(&server_addr, 0, 
 86  sizeof(struct sockaddr_un));
 87  server_addr.sun_family = AF_UNIX;
 88  strncpy(server_addr.sun_path, 
 89  SOCKET_PATH, 
 90  sizeof(server_addr.sun_path) - 1);
 91
 92  client_fd = socket(AF_UNIX, 
 93              SOCK_STREAM, 0);
 94  
 95  if (client_fd < 0) {
 96    perror("socket");
 97    return -1;
 98  }
 99
100  cli_connect = connect(client_fd, 
101  (struct sockaddr*)&server_addr, 
102  sizeof(struct sockaddr_un));
103
104 if (cli_connect < 0) {
105   perror("connect");
106   (void)close(client_fd);
107   return -2;
108 }
109
110  while (1) {
111   send_data(buffer);
112
113   FD_ZERO(&read_fds);
114   FD_SET(client_fd, &read_fds);
115
116   ret = select(client_fd + 1, 
117   &read_fds, NULL, NULL, NULL);
118
119   if (ret < 0) {  
120      perror("select");
121      break;
122    }
123
124    if (FD_ISSET(client_fd, 
125       &read_fds)) {
126       recv_data(buffer);
127    }
128  }
129
130  (void)close(client_fd);
131  
132  return 0;
133}
 1$ gcc -o client client.c
 2
 3$ sudo ./client
 4
 5sentbuffer = HI
 6Received: HELLO
 7sentbuffer = HI
 8Received: HELLO
 9sentbuffer = HI
10Received: HELLO
11sentbuffer = HI
12Received: HELLO
13sentbuffer = HI
14Received: HELLO
15sentbuffer = HI
16Received: HELLO
17sentbuffer = HI
18Received: HELLO
19sentbuffer = HI
20Received: HELLO
21sentbuffer = HI
22^CCaught sigINT!

Socket API

Learning

socket

Create a new socket

bind

Associate the socket with a specific address and port

listen

Set up a socket to accept incoming connections.

connect

Establish a connection from a client to a server.

accept

Server side to accept a connection request from a client.

select

Monitor multiple file descriptors (usually sockets) for read, write, or error conditions.

recv

Receive data from a connected socket.

send

Send data over a connected socket.