Simple TCP Server and Client
Just as we start with any programming language, we will implement a simple hello world program in socket programming.
In this article, we will implement a simple TCP server and client.
- The server will listen on a specific port and IP address.
- The client will connect to the server and send data to it.
- After receiving the data, the server will send a response back to the client.
- The client will receive the response and print it.
Program Flowchart

image
Source: Socket Programming in C/C++ - GeeksforGeeks
Server Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#define IPADDR "127.0.0.1" /* Server IP address */
#define PORT 43866 /* Port number */
#define STRING_LEN_16 16
#define STRING_LEN_64 64
#define BACKLOG 10
char *_inet_ntoa(struct in_addr *addr, char *ipAddr, int len)
{
// Convert binary IP address to a human-readable IP address
if (NULL == addr || NULL == ipAddr || 16 > len)
{
printf("invalid param\n");
return NULL;
}
unsigned char *tmp = (unsigned char *)addr;
snprintf(ipAddr, len, "%d.%d.%d.%d", tmp[0], tmp[1], tmp[2], tmp[3]);
return ipAddr;
}
int main(int argc, char *argv[])
{
// 1. Create a socket socket()
int sockfd = socket(AF_INET, SOCK_STREAM, 0); // TCP socket
if (sockfd == -1)
{
printf("fail to call socket, errno[%d, %s]\n", errno, strerror(errno));
exit(0);
}
// Manually build the sockaddr_in structure
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr)); // Initialize the structure to 0
addr.sin_family = AF_INET; // IPv4
addr.sin_port = htons(PORT); // Port number
inet_aton(IPADDR, &addr.sin_addr); // Convert human-readable IP address to binary IP address
// inet_aton is now deprecated because it does not support IPv6
// 2. Bind the socket to a specific IP address and port bind()
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
printf("fail to call bind, errno[%d, %s]\n", errno, strerror(errno));
close(sockfd);
exit(0);
}
// 3. Put the socket into passive listening state listen()
if (listen(sockfd, BACKLOG) == -1)
{
printf("fail to call listen, errno[%d, %s]\n", errno, strerror(errno));
close(sockfd);
exit(0);
}
printf("server listen on %s:%u\n", IPADDR, PORT);
// 4. When the socket is listening, use the accept function to receive client requests accept()
struct sockaddr_in peerAddr;
socklen_t peerAddrLen = sizeof(struct sockaddr_in);
int connfd = accept(sockfd, (struct sockaddr *)&peerAddr, &peerAddrLen);
if (connfd == -1)
{
printf("fail to call accept, errno[%d, %s]\n", errno, strerror(errno));
close(sockfd);
exit(0);
}
char peerIPAddr[STRING_LEN_16];
_inet_ntoa(&peerAddr.sin_addr, peerIPAddr, STRING_LEN_16);
printf("peer client address [%s:%u]\n", peerIPAddr, ntohs(peerAddr.sin_port));
while (1)
{
// 5. Read data sent by the client recv()
char buf[STRING_LEN_64];
int n = recv(connfd, buf, STRING_LEN_64 - 1, 0);
buf[n] = '\0';
if (0 == n) // n == 0 means the peer closed the connection
{
printf("peer close\n");
break;
}
printf("recv msg from client : %s\n", buf);
sleep(2);
// 6. Send data to the client send()
char str[] = "recved!";
printf("send msg to client : %s\n", str);
send(connfd, str, strlen(str), 0);
}
// 7. Interaction ends, close the socket close()
close(connfd);
close(sockfd);
return 0;
}
Client Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#define IPADDR "127.0.0.1" /* Server IP address */
#define PORT 43866 /* Server port number */
#define STRING_LEN_64 64
int main()
{
// 1. Create a TCP socket socket()
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
printf("sockfd = %d\n", sockfd);
if (-1 == sockfd)
{
printf("fail to call socket, errno[%d, %s]\n", errno, strerror(errno));
exit(0);
}
// 2. Connect the socket to a specific IP address and port number connect()
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_aton(IPADDR, &addr.sin_addr);
if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
printf("fail to call connect, errno[%d, %s]\n", errno, strerror(errno));
close(sockfd);
exit(0);
}
// 3. Send data to the server through the socket send()
char str[] = "hello world";
printf("send msg to server : %s\n", str);
send(sockfd, str, strlen(str), 0);
// 4. Receive data from the server through the socket recv()
char buf[STRING_LEN_64];
int n = recv(sockfd, buf, STRING_LEN_64 - 1, 0);
buf[n] = '\0';
printf("recv msg from server : %s\n", buf);
// 5. Interaction ends, close the socket close()
close(sockfd);
}
Compilation and Execution
Compiling:
gcc client.c -o client
gcc server.c -o server
Output
$ ./server # run server on server terminal
server listen on 127.0.0.1:43866
peer client address [127.0.0.1:33844]
recv msg from client : hello world
send msg to client : recved!
peer close
$ ./client # run client on client terminal
sockfd = 3
send msg to server : hello world
recv msg from server : recved!
Potential Issues
- The server program can only serve one client at a time.
- The code does not support IPv6. (inetntoa, inetaton)
- The program has no security measures. It does not authenticate the client or encrypt communication, making it vulnerable to attacks such as spoofing or eavesdropping.
Solutions
- Use select() to handle multiple clients.
- Use getaddrinfo(), ntop(), and pton() to support IPv6.
- Use SSL/TLS to encrypt communication.