Client server communication using sockets in C

Client server communication using Sockets and TCP in C part 2

This post in in continuation with client server communication using Socket and TCP in C Part 1. Here in this post, we are gonna implement server side of communication using C. Here is code snippet for the same:


/****************** SERVER CODE ****************/

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

int main(){
int welcomeSocket, newSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;

/*—- Create the socket. The three arguments are: —-*/
/* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);

/*—- Configure settings of the server address struct —-*/
/* Address family = Internet */
serverAddr.sin_family = AF_INET;
/* Set port number, using htons function to use proper byte order */
serverAddr.sin_port = htons(7891);
/* Set IP address to localhost */
serverAddr.sin_addr.s_addr = inet_addr(“”);
/* Set all bits of the padding field to 0 */
memset(serverAddr.sin_zero, ‘\0’, sizeof serverAddr.sin_zero);

/*—- Bind the address struct to the socket —-*/
bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

/*—- Listen on the socket, with 5 max connection requests queued —-*/

/*—- Accept call creates a new socket for the incoming connection —-*/
addr_size = sizeof serverStorage;
newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);

/*—- Send message to the socket of the incoming connection —-*/
strcpy(buffer,”Hello World\n”);

return 0;


Thanks for dropping by !! Feel free to comment to this post or you can drop me an email at

Leave a Reply

Your email address will not be published. Required fields are marked *