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?
See Answer
AF_UNIX
represents the Unix domain socket family.
It is used for communication between processes on the same machine, using file system paths as addresses.
Why use SOCK_STREAM as the socket type?
See Answer
SOCK_STREAM
indicates a stream-oriented socket, providing a reliable, connection-oriented communication channel.
What does the third parameter (0) indicate in socket(AF_UNIX, SOCK_STREAM, 0)?
See Answer
Default protocol selected by the system.
How can I set up a server and client using AF_UNIX sockets?
See Answer
To set up a server and client,
create a socket using socket(AF_UNIX, SOCK_STREAM, 0),
bind the server to an address,
isten for incoming connections, and establish connections from clients.
Communication occurs through read and write operations on the established connections.
How should errors in the socket call be handled?
See Answer
Check the return value, handle errors using appropriate mechanisms.
What is the role of the file system path in AF_UNIX sockets?
See Answer
The file system path serves as the address for Unix domain sockets.
It enables processes to locate and connect to the socket.
he path is set in the sun_path
field of the struct sockaddr_un
structure.
What is the role of the file system path in AF_UNIX sockets?
See Answer
Address.
Why might bind() or listen() fail in socket programming?
See Answer
bind() might fail if the specified address is already in use, or if the process lacks the necessary permissions. listen() might fail if the socket is not bound, or the operating system limit for pending connections is reached.
How should you handle errors when using accept() in socket programming?
See Answer
Check the return value and handle errors appropriately
Why is it important to check the return value of send() and recv() in socket programming?
See Answer
It detects issues such as network errors or closed connections.
What is the purpose of the select system call in network programming?
See Answer
To block and wait for activity on one or more file descriptors.
How does select help in handling multiple sockets efficiently?
See Answer
It provides a way to wait for readiness on multiple sockets without blocking the entire program.
What types of file descriptors can be monitored using select?
See Answer
sockets, files, timerfd, socketpair, message_queue, Namedpipes and shared_memory.
What is the significance of the timeout parameter in the select function?
See Answer
It specifies the maximum duration to wait for any file descriptor to become ready.
How do you handle errors when using the select system call?
See Answer
Check the return value for -1 to detect errors, Use perror to print error messages.
How does select handle a set of file descriptors with different states (e.g., reading, writing, exception)?
See Answer
- Preparing File Descriptor Sets:
select(readfds, writefds, exceptfds);
- Setting Up Readiness Conditions:
If you are interested in monitoring file descriptors for readability, you add them to the readfds set.
FD_ZERO(&readfds);
FD_SET(fd1, &readfds);
- Setting Up Writability Conditions:
If you are interested in monitoring file descriptors for writability, you add them to the writefds set.
FD_ZERO(&writefds);
FD_SET(fd2, &writefds);
- Setting Up Exceptional Conditions:
If you are interested in monitoring file descriptors for exceptional conditions, you add them to the exceptfds set.
FD_ZERO(&exceptfds);
FD_SET(fd3, &exceptfds);
How does select Checking Ready File Descriptors?
See Answer
After select returns, you can check the sets to determine which file descriptors are ready for the specified conditions.
if (FD_ISSET(fd1, &readfds)) {
// fd1 is ready for reading
}
if (FD_ISSET(fd3, &writefds)) {
// fd2 is ready for writing
}
if (FD_ISSET(fd4, &exceptfds)) {
// fd3 has an exceptional condition
}
What does it mean if select 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
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!
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. |
Previous topic
Current topic
Next topic
Other sockets
Other IPCs