This post doesn’t provide details about how Linux socket works, its design etc. It mainly for providing source code of simple TCP socket client and server in C. I’m writing this because I found myself need simple TCP client and server for testing from time to time. 🙂
1. The TCP Server Code
You can refer to TCP Server code below (save it as tcpserver.c),
The code first create a socket of SOCK_STREAM type in AF_INET domain. SOCK_STREAM corresponds to TCP, and AF_INET refers to IPv4.
It calls setsockopt to make the socket resuable. For example, your server open up a socket at a port number, and then it exits. Without this line of code, sometimes you may not bind the socket to same port.
The program then binds the socket to a local IP address with a specific port number. listen(sockfd, 5) will set the socket as passive socket listening to incoming connections. 5 means the maximum number of backlog is 5. Backlog connections are pending connect request in queue. If pending request are more than 5, later request may be ignored.
The code then calls accept method to accept incoming connections. This is a block call, and it returns when a new connect request is received, or an error occurred.
In the for loop, the tcp server listens to incoming packets and echo the message back. Note that the nonblock(newsockfd) has been commented out. You can uncomment it to enable nonblock read and write, but you may want to modify the read and write part to make it work properly.
2. The TCP Client Code
The TCP client code is as below (save it as tcpclient.c),
The code creates a TCP socket. It then tries to connect to a server address with specified IP and port number. The connect is a block call, it returns when the connection is established, which means it receives the ACK from tcp server, which is third packet of TCP 3-way handshake (SYN, ACK+SYN, ACK).
In the loop the tcp client sends and receives messages. Also the nonblock code has been disabled.
3. Compile and Run
To compile the code, use the commands below,
gcc -o client tcpclient.c
gcc -o server tcpserver.c
A sample run could be,
./server 12345 (at one terminal)
./client localhost 12345 (at another terminal)