Simple TCP Server and Client (Improved Version)
Introduction
Compared to the Simple TCP Server and Client, the server and client programs in this article have been improved in the following ways:
- Uses
inet_ntop()so the server can correctly handle both IPv4 and IPv6 addresses. - Uses
getaddrinfo()so the server can correctly handle both IPv4 and IPv6 addresses. - Uses
fork()so the server can handle connection requests from multiple clients simultaneously. - Uses
waitpid()so the server can correctly handle child process termination.
Server Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define PORT "43866" /* Port number */
#define BACKLOG 10 /* Maximum pending connections */
#define MAXDATASIZE 100 /* Maximum data transfer size */
/* Signal handler for child process termination */
void sigchld_handler(int s)
{
/* Save errno because waitpid() might change it */
int saved_errno = errno;
/* Reap all dead child processes */
while (waitpid(-1, NULL, WNOHANG) > 0)
;
/* Restore errno */
errno = saved_errno;
}
/* Get the IP address from a sockaddr structure */
void *get_in_addr(struct sockaddr *sa)
{
/* Check the address family */
if (sa->sa_family == AF_INET)
{
/* Return the IPv4 address */
return &(((struct sockaddr_in *)sa)->sin_addr);
}
/* Return the IPv6 address */
return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}
/* Get the port number from a sockaddr structure */
int get_in_port(struct sockaddr *sa)
{
/* Check the address family */
if (sa->sa_family == AF_INET)
{
/* Return the IPv4 port */
return (((struct sockaddr_in *)sa)->sin_port);
}
/* Return the IPv6 port */
return (((struct sockaddr_in6 *)sa)->sin6_port);
}
/* Main function */
int main(int argc, char *argv[])
{
int sockfd, new_fd; /* sockfd: listening socket, new_fd: data transfer socket */
struct addrinfo hints, *servinfo, *p; /* hints: configure addrinfo, servinfo: address info, p: pointer to traverse servinfo */
struct sockaddr_storage their_addr; /* Client IP address and port info */
socklen_t sin_size; /* For accept() */
struct sigaction sa; /* For sigaction() */
int yes = 1; /* For setsockopt() */
int rv; /* Return value of getaddrinfo() */
char s[INET6_ADDRSTRLEN]; /* String for inet_ntop() address */
int numbytes_send; /* Return value of send() */
int numbytes_recv; /* Return value of recv() */
char buf[MAXDATASIZE]; /* Buffer for received data */
/* Initialize the hints structure */
memset(&hints, 0, sizeof hints);
/* Set up the hints structure */
hints.ai_family = AF_UNSPEC; /* Don't specify IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP stream sockets */
hints.ai_flags = AI_PASSIVE; /* Use my IP */
/* Get address info */
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0)
{
/* Print error message */
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
/* Loop through the linked list of servinfo */
for (p = servinfo; p != NULL; p = p->ai_next)
{
/* Create a socket */
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
/* Print error message */
perror("server: socket");
continue;
}
/* Set socket options */
// SO_REUSEADDR allows reuse of local addresses and ports
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
/* Print error message */
perror("setsockopt");
exit(1);
}
/* Bind the socket */
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
/* Failed to connect to server */
close(sockfd);
perror("server: bind");
continue;
}
break;
}
/* Free the results linked list */
freeaddrinfo(servinfo);
/* Check if binding was successful */
if (p == NULL)
{
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
/* Listen on the socket */
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
/* Signal handler */
sa.sa_handler = sigchld_handler; /* Reap all zombie processes */
sigemptyset(&sa.sa_mask); /* Block all signals */
sa.sa_flags = SA_RESTART; /* Restart interrupted system calls */
if (sigaction(SIGCHLD, &sa, NULL) == -1)
{
/* Print error message */
perror("sigaction");
exit(1);
}
printf("server: waiting for connections...\n");
/* Main loop for accept() */
while (1)
{
sin_size = sizeof their_addr;
/* Accept a connection request */
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1)
{ /* Failed to accept connection */
perror("accept");
continue;
}
/* Convert IP address to string */
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
printf("server: got connection from %s, port %d, socketfd %d\n", s, ntohs(get_in_port((struct sockaddr *)&their_addr)), new_fd);
/* Fork a child process to handle the new connection */
if (!fork())
{
/* Child process doesn't need the listening socket */
close(sockfd);
/* Child process handles data transfer */
/* Build the message to send */
char *msg = "Hello world from server!";
int msg_len = strlen(msg);
/* Send message to client */
if ((numbytes_send = send(new_fd, msg, msg_len, 0)) == -1)
perror("send");
/* Print sent message */
printf("server: sent message: %s (%d bytes) to %s, port %d, sockfd %d\n", msg, numbytes_send, s, ntohs(get_in_port((struct sockaddr *)&their_addr)), new_fd);
/* Receive message from client */
if ((numbytes_recv = recv(new_fd, buf, MAXDATASIZE - 1, 0)) == -1)
{
perror("recv");
exit(1);
}
buf[numbytes_recv] = '\0';
printf("server: received message: %s (%d bytes) from %s, port %d, sockfd %d\n", buf, numbytes_recv, s, ntohs(get_in_port((struct sockaddr *)&their_addr)), new_fd);
/* Close the data transfer socket */
close(new_fd);
printf("\n");
/* Exit child process */
exit(0);
}
/* Parent process doesn't need the data transfer socket */
close(new_fd);
}
return 0;
}
/* References: Page 31-33, Beej's Guide to Network Programming Using Internet Sockets */
Client Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "43866" /* Port number */
#define MAXDATASIZE 100 /* Maximum data transfer size per call */
/* Get sockaddr, IPv4 or IPv6: */
void *get_in_addr(struct sockaddr *sa)
{
/* Check the address family */
if (sa->sa_family == AF_INET)
{
/* Return the IPv4 address */
return &(((struct sockaddr_in *)sa)->sin_addr);
}
/* Return the IPv6 address */
return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int sockfd; /* sockfd: return value of socket() */
char buf[MAXDATASIZE]; /* Buffer for received data */
struct addrinfo hints, *servinfo, *p; /* hints: configure addrinfo, servinfo: address info, p: pointer to traverse servinfo */
int rv; /* Return value of getaddrinfo() */
char s[INET6_ADDRSTRLEN]; /* String for inet_ntop() address */
int numbytes_recv; /* Return value of recv() */
int numbytes_send; /* Return value of send() */
/* Check number of arguments */
if (argc != 2)
{
fprintf(stderr, "usage: ./client hostname\n");
exit(1);
}
/* Initialize the hints structure */
memset(&hints, 0, sizeof hints);
/* Set up the hints structure */
hints.ai_family = AF_UNSPEC; /* Don't specify IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP stream sockets */
/* Get address info */
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0)
{
/* Print error message */
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
/* Loop through the linked list of servinfo */
for (p = servinfo; p != NULL; p = p->ai_next)
{
/* Create a socket */
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
/* Print error message */
perror("client: socket");
continue;
}
/* Connect to the server */
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
/* Failed to connect to server */
close(sockfd);
perror("client: connect");
continue;
}
break;
}
/* Finished traversing servinfo, still no connection */
if (p == NULL)
{
fprintf(stderr, "client: failed to connect to server\n"); /* Send data to server */
return 2;
}
/* Convert address info to string */
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
/* Print the server address we connected to */
printf("client: connecting to %s port %s\n", s, PORT);
/* Free the servinfo structure */
freeaddrinfo(servinfo);
/* Receive data */
if ((numbytes_recv = recv(sockfd, buf, MAXDATASIZE - 1, 0)) == -1)
{
/* Failed to receive data */
perror("recv");
exit(1);
}
/* Null-terminate the string */
buf[numbytes_recv] = '\0';
/* Print received data */
printf("client: received '%s' from server.\n", buf);
/* Build the data to send */
char *msg = "Hello world from client!";
int msg_len = strlen(msg);
/* Send data to server */
if ((numbytes_send = send(sockfd, msg, msg_len, 0)) == -1)
{
/* Failed to send data */
perror("send");
}
printf("client: sent '%s' (%d bytes) to server.\n", msg, numbytes_send);
/* Close the socket */
close(sockfd);
printf("client: closed socketfd %d.\n", sockfd);
return 0;
}
/* References: Page 31-33, Beej's Guide to Network Programming Using Internet Sockets */
Compilation
gcc server.c -o server
gcc client.c -o client
Running and Output
$ ./server
server: waiting for connections...
server: got connection from 127.0.0.1, port 56836, socketfd 4
server: sent message: Hello world from server! (24 bytes) to 127.0.0.1, port 56836, sockfd 4
server: received message: Hello world from client! (24 bytes) from 127.0.0.1, port 56836, sockfd 4
$ ./client localhost
client: connecting to
client: received 'Hello world from server!' from server.
client: sent 'Hello world from client!' (24 bytes) to server.
client: closed socketfd 3
If you run the client before the server, you will see the following error:
$ ./client localhost
client: connect: Connection refused
client: failed to connect to server
References
A Simple Stream Server - Beej’s Guide to Network Programming
A Simple Stream Client - Beej’s Guide to Network Programming
CC BY-NC-SA 4.0 · pintaste
Comments
Giscus comments activate once PUBLIC_GISCUS_* env vars are set.