What is a simple C or C++ TCP server and client example?

Nick Bolton picture Nick Bolton · Mar 19, 2009 · Viewed 141.1k times · Source

I need to quickly implement a very small C or C++ TCP server/client solution. This is simply to transfer literally an array of bytes from one computer to another - doesn't need to be scalable / over-complicated. The simpler the better. Quick and dirty if you can.

I tried to use the code from this tutorial, but I couldn't get it to build using g++ in Linux: http://www.linuxhowtos.org/C_C++/socket.htm

If possible, I'd like to avoid 3rd party libraries, as the system I'm running this on is quite restricted. This must be C or C++ as the existing application is already implemented.

Thanks to emg-2's answer, I managed to make the above mentioned code sample compatible with C++ using the following steps:

Add these headers to both client and server:

#include <cstdlib>
#include <cstring>
#include <unistd.h>

In server.c, change the type of clilen to socklen_t.

int sockfd, newsockfd, portno/*, clilen*/;
socklen_t clilen;

In client.c, change the following line:

if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) { ... }

To:

if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)

Answer

Bill the Lizard picture Bill the Lizard · Mar 19, 2009

I've used Beej's Guide to Network Programming in the past. It's in C, not C++, but the examples are good. Go directly to section 6 for the simple client and server example programs.