Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

How to implement simple TCP Client and Server Program in C?

How to implement simple TCP Client and Server Program in C?

This is a C Program that illustrates a simple TCP (Transmission Control Protocol) server that accepts incoming client connections. Once a client connection is established, a thread is spawned to read data from the client and echo it back (if the echo option is not disabled).

You can use any C/C++ Compilers in windows to compile and run this program as it uses winsock2 windows network API.

How to Compile the TCP Client/Server program?

The following TCP Client Server program is divided into two parts, the server and the client. Please compile each program separately as per the following instructions.

Server:

To compile the server program, use the following command line. TCP server accepts incoming client connections. Once a client connection is established, a thread is spawned to read data from the client and echo it back (if the echo option is not disabled).

Compile:

cl -o Server Server.c ws2_32.lib

Command line options:
server [-p:x] [-i:IP] [-o]
-p:x Port number to listen on
-i:str Interface to listen on
-o Receive only, don’t echo the data back

Client:

This sample is the echo client. It connects to the TCP server, sends data, and reads data back from the server.

Compile:
cl -o Client Client.c ws2_32.lib

Command Line Options:

C++ For Dummies 7th Edition
Unlock the world of programming with C++ for Dummies – the perfect beginner’s guide to mastering C++ with ease and confidence!
View on Amazon

client [-p:x] [-s:IP] [-n:x] [-o]
-p:x Remote port to send to
-s:IP Server’s IP address or hostname
-n:x Number of times to send message
-o Send messages only; don’t receive

Client Source Code

Server Source Code

About The Author

M. Saqib

Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.