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
CodeBlock Loading...
Client Code
C
#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
BASH
gcc server.c -o server
gcc client.c -o client
Running and Output
BASH
$ ./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
CodeBlock Loading...
If you run the client before the server, you will see the following error:
BASH
$ ./client localhost
client: connect: Connection refused
client: failed to connect to server