Socket Programming- TCP client

2 01 2008

This a very basic tutorial for TCP server-client.

The code against tcp-server , the Clients Code

#define SRVR_PORT 4030 // The Server’s Port which Client is going to Connect.

#define MAXBUFLEN 100// Buffer Size for Sending/Receiving

int main(int argc, char *argv[])

int sockfd;
struct sockaddr_in their_addr; // connector’s address information
struct hostent *he;
int numbytes;
char buf[MAXBUFLEN];

//The Code to Take Server’s Address at Commandline

//You can remove this and assign your server’s Address you want

if (argc != 2)
fprintf(stderr,”usage: ./client\n”);

if ((he=gethostbyname(argv[1])) == NULL) { // get the host info

//Creating the Socket(The Door for Communication)

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

//Setting the Attributes for Server Address

their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(SRVR_PORT); // short, network byte order
their_addr.sin_addr.s_addr = inet_addr(“″);//*((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero),”,8); // zero the rest

int addrlen = sizeof(struct sockaddr);

//Connecting to The Server

//connect return the status for successful connection or failure

int status;
status = connect(sockfd,(struct sockaddr*)&their_addr,addrlen);


//Taking Input msg from Console

//Remove this if you not want from console Then use strcpy to fill the buffer

cout << “Enter ur message: “;

//The buffer conatain the message you want to send to server

// The send method sends to the sevrer , just give socket id , buffer , and buffer size to send

// and off course give error on failure

if ( (numbytes=send(sockfd, buf, strlen(buf) , 0)) == -1)

// To Nullify or Empty to the buffer use memset method


// The recv method is used for tcp recive , just sock id, buffer in which recv and length

// method return non-positive value for error

if ((numbytes=recv((int)sockfd,buf, MAXBUFLEN-1, 0)) == -1)

cout << “from server>” << buf << endl;


printf(“sent %d bytes to %s\n”, numbytes,inet_ntoa(their_addr.sin_addr));

close(sockfd); // It’s good to close the socket(the door) after Communication

return 0;


Let me know if you not uderstand any thing. I will upload the complete source code.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: