IPV4 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 the AF_INET parameter represent in the socket() function call?
See Answer
Address Family for IPv4
Why is SOCK_STREAM used as the second parameter in the socket() function call?
See Answer
It indicates that the socket will use a reliable, connection-oriented communication (TCP).
What is the default protocol for a TCP socket created with socket(AF_INET, SOCK_STREAM, ?? )?
See Answer
IPPROTO_TCP
What is the primary characteristic of TCP communication?
See Answer
Connection-oriented and reliable
What does a return value of -1 indicate in socket functions?
See Answer
In many socket programming APIs, a return value of -1 usually indicates an error. Functions often set an error code that can be retrieved using perror (or an equivalent mechanism) to determine the specific nature of the error.
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 a common practice for handling timeouts in socket programming?
See Answer
Use non-blocking sockets with functions like select() or poll().
Can you use a TCP socket (SOCK_STREAM) for sending and receiving data concurrently between a client and server?
See Answer
Yes, TCP sockets support bidirectional communication.
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_INET, SOCK_STREAM, IPPROTO_TCP);
bind()
is used to associate the socket with a specific address and port. For example,
ret = bind(tcp_server_fd, (struct sockaddr*)&tcp_addr, sizeof(tcp_addr));
listen()
is used to set up a socket to accept incoming connections. For example,
ret = listen(tcp_server_fd, 5);
accept()
is used in network programming on the server side to accept a connection request from a client. For example,
tcp_client_fd = accept(tcp_server_fd, (struct sockaddr*) &tcp_addr, &tcp_addr_len);
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(tcp_client_fd, buffer, sizeof(buffer) - 1, 0);
send
is used in network programming to send data over a connected socket. For example,
ret = send(tcp_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(tcp_client_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 <sys/types.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <signal.h>
int tcp_server_fd = -1;
int tcp_client_fd = -1;
static void sigint_handler(int signo)
{
(void)close(tcp_server_fd);
(void)close(tcp_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 validate_convert_port(
char *port_str,
struct sockaddr_in *sock_addr)
{
int port;
if (port_str == NULL) {
perror("Invalid port_str\n");
exit(EXIT_FAILURE);
}
if (sock_addr == NULL) {
perror("Invalid sock_addr\n");
exit(EXIT_FAILURE);
}
port = atoi(port_str);
if (port == 0) {
perror("Invalid port\n");
exit(EXIT_FAILURE);
}
sock_addr->sin_port = htons(
(uint16_t)port);
printf("Port: %d\n",
ntohs(sock_addr->sin_port));
}
void recv_send(char *buffer)
{
int len, ret;
memset(buffer, 0, sizeof(buffer));
len = recv(tcp_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(tcp_client_fd, buffer,
strlen(buffer), 0);
if (ret < 0) {
perror("send error\n");
(void)close(tcp_client_fd);
(void)close(tcp_server_fd);
exit(EXIT_FAILURE);
}
} else if (len < 0) {
perror("recv");
(void)close(tcp_client_fd);
(void)close(tcp_server_fd);
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
int fdmax = 0;
int flag = 0;
int ret;
struct sockaddr_in
tcp_addr;
fd_set read_fds;
char buffer[1024];
socklen_t tcp_addr_len = sizeof(
tcp_addr);
register_signal_handler(SIGINT,
sigint_handler);
if (argc != 2) {
printf("%s <port-number>",
argv[0]);
exit(EXIT_FAILURE);
}
memset(&tcp_addr, 0,
sizeof(tcp_addr));
tcp_addr.sin_family = AF_INET;
tcp_addr.sin_addr.s_addr =
INADDR_ANY;
validate_convert_port(argv[1],
&tcp_addr);
tcp_server_fd = socket(AF_INET,
SOCK_STREAM,
IPPROTO_TCP);
if (tcp_server_fd < 0) {
perror("socket");
return -1;
}
ret = bind(tcp_server_fd,
(struct sockaddr *)&tcp_addr,
sizeof(tcp_addr));
if (ret < 0)
{
perror("bind");
(void)close(tcp_server_fd);
return -2;
}
ret = listen(tcp_server_fd, 5);
if (ret < 0)
{
perror("listen");
(void)close(tcp_server_fd);
return -3;
}
tcp_client_fd = accept(tcp_server_fd,
(struct sockaddr *) &tcp_addr,
&tcp_addr_len);
if (tcp_client_fd < 0) {
perror("accept");
(void)close(tcp_server_fd);
return -4;
}
(void)printf("Server lsiten...\n");
fdmax = tcp_client_fd;
while (1) {
FD_ZERO(&read_fds);
FD_SET(tcp_client_fd, &read_fds);
ret = select(fdmax + 1, &read_fds,
NULL, NULL, NULL);
if (ret < 0) {
perror("select");
break;
}
if (FD_ISSET(tcp_client_fd,
&read_fds)) {
recv_send(buffer);
}
}
(void)close(tcp_client_fd);
(void)close(tcp_server_fd);
return 0;
}
1$ gcc -o server server.c
2
3$ sudo ./server 8080
4
5Port: 8080
6Server lsiten...
7connection = 4
8Received: HI
9Sentbuffer = HELLO
10Received: HI
11Sentbuffer = HELLO
12Received: HI
13Sentbuffer = HELLO
14Received: HI
15Sentbuffer = HELLO
16Received: HI
17Sentbuffer = HELLO
18Received: HI
19Sentbuffer = HELLO
20Received: HI
21Sentbuffer = HELLO
22Received: HI
23Sentbuffer = HELLO
24Received: HI
25Sentbuffer = HELLO
26Received: HI
27^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_INET, SOCK_STREAM, IPPROTO_TCP);
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*)&tcp_addr, tcp_addr_len);
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,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <signal.h>
int client_fd = -1;
static void sigint_handler(int signo)
{
(void)close(client_fd);
sleep(2);
(void)printf("Caught sigINT!\n");
exit(EXIT_SUCCESS);
}
void validate_convert_port(
char *port_str,
struct sockaddr_in *sock_addr)
{
int port;
if (port_str == NULL) {
perror("Invalid port_str\n");
exit(EXIT_FAILURE);
}
if (sock_addr == NULL) {
perror("Invalid sock_addr\n");
exit(EXIT_FAILURE);
}
port = atoi(port_str);
if (port == 0) {
perror("Invalid port\n");
exit(EXIT_FAILURE);
}
sock_addr->sin_port = htons(
(uint16_t)port);
printf("Port: %d\n",
ntohs(sock_addr->sin_port));
}
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 recv_data(char *buffer)
{
int ret, len;
len = recv(client_fd, buffer,
sizeof(buffer) - 1, 0);
if (len > 0) {
buffer[len] = '\0';
(void)printf("Received: %s\n",
buffer);
} else if (len == 0) {
printf("Connection closed\n");
exit(EXIT_FAILURE);
}
}
void send_data(char *buffer)
{
int ret;
memset(buffer, 0, sizeof(buffer));
strncpy(buffer, "HI",
strlen("HI") + 1);
buffer[strlen(buffer) + 1] = '\0';
ret = send(client_fd, buffer,
strlen(buffer), 0);
if (ret < 0) {
perror("send error\n");
(void)close(client_fd);
exit(EXIT_FAILURE);
}
printf("sentbuffer = %s\n",
buffer);
}
void register_signal_handler(
int signum,
void (*handler)(int))
{
if (signal(signum, handler) == SIG_ERR)
{
printf("Cannot handle signal\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
int cli_connect;
int ret;
struct sockaddr_in
tcp_addr;
fd_set read_fds;
char buffer[1024];
socklen_t tcp_addr_len = sizeof(
tcp_addr);
register_signal_handler(SIGINT,
sigint_handler);
if (argc != 3) {
printf("%s<port-number><ip-addr>\n",
argv[0]);
exit(EXIT_FAILURE);
}
memset(&tcp_addr, 0,
sizeof(tcp_addr));
tcp_addr.sin_family = AF_INET;
validate_convert_port(argv[1],
&tcp_addr);
validate_convert_addr(argv[2],
&tcp_addr);
client_fd = socket(AF_INET,
SOCK_STREAM,
IPPROTO_TCP);
if (client_fd < 0) {
perror("socket");
return -1;
}
cli_connect = connect(client_fd,
(struct sockaddr *)&tcp_addr,
tcp_addr_len);
if (cli_connect < 0) {
perror("connect");
return -2;
} else {
printf("connected\n");
}
while (1) {
send_data(buffer);
FD_ZERO(&read_fds);
FD_SET(client_fd, &read_fds);
ret = select(client_fd + 1,
&read_fds, NULL, NULL, NULL);
if (ret < 0) {
perror("select");
break;
}
if (FD_ISSET(client_fd,
&read_fds)) {
recv_data(buffer);
}
}
(void)close(client_fd);
return 0;
}
1$ gcc -o client client.c
2
3$ sudo ./client 8080 127.0.0.1
4
5Port: 8080
6IP Address: 127.0.0.1
7Received: HELLO
8Sentbuffer = HI
9Received: HELLO
10Sentbuffer = HI
11Received: HELLO
12Sentbuffer = HI
13Received: HELLO
14Sentbuffer = HI
15Received: HELLO
16Sentbuffer = HI
17Received: HELLO
18Sentbuffer = HI
19Received: HELLO
20Sentbuffer = HI
21Received: HELLO
22^CCaught sigINT!
$ sudo ./server 8080 127.0.0.1
$ sudo ./client 8080 127.0.0.1
program to run with elevated privileges, listen on port 8080, and bind to the loopback address 127.0.0.1.
<port_number> <ip_address> decided by the user based on the connection.
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_STREAM, 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 |
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