Click here to Skip to main content
15,861,125 members
Articles / Desktop Programming / MFC
Article

Beginning Winsock Programming - Simple TCP client

Rate me:
Please Sign up or sign in to vote.
4.83/5 (87 votes)
28 Feb 2002CPOL4 min read 669.6K   17.4K   222   76
A simple TCP client is explained.

Image 1

Introduction

This is a sequel to the article Beginning Winsock Programming - Simple TCP server and if you have not read that already I would recommend that you do that first. In this article I'll show how you can write a simple TCP client program. We'll write a program that will connect to an HTTP server and retrieve a file.

Program Flow of a simple TCP client

  1. Initialize WinSock library using WSAStartup()
  2. Create a IPPROTO_TCP SOCKET using socket()
  3. Retrieve host information using gethostbyname()/gethostbyaddr()
  4. Connect to the server using the socket we created, using connect()
  5. Send and Receive data using send()/recv() till our tcp chat is over
  6. Close the socket connection using closesocket()
  7. De-Initialize WinSock using WSACleanup()

Initialize WinSock

As with every other WinSock program we need to initialize the WinSock library. Basically it is also a kind of check to see if WinSock is available on the system in the precise version we expect it to be.

int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret)	
    return;

Create the SOCKET

The socket is the entity that acts as the endpoint between the client and the server. When a client is connected to a server, there are two sockets. The socket at the client side and the corresponding socket at the server side. Lets call them CLIENTSOCK and SERVERSOCK. When the client uses send() on CLIENTSOCK the server can use recv() on the SERVERSOCK to receive what the client sends. Similarly the reverse is also true. For our purposes we create the socket using a function called socket().

SOCKET conn;
conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(conn==INVALID_SOCKET)
    return;

Getting host information

Obviously we need to get info about the host [the server] before we can connect to it. There are two functions we can use - gethostbyname() and gethostbyaddr(). The gethostbyname() function is used when we have the DNS name of our server, something like codeproject.com or ftp.myserver.org. The

gethostbyaddr()
function is used when we actually have the IP address of the server to connect to, something like 192.168.1.1 or 202.54.1.100.

Obviously we would want to give our end user the option of entering either a DNS name or an IP address. Thus for making that part of it transparent to him, we do a little trick as shown below. We use the function inet_addr() on the entered string. The inet_addr() function converts an IP address into a standard network address format. Thus if it returns failure, we now know that the string cannot be an IP address, if it succeeds we assume that it was a valid IP address.

if(inet_addr(servername)==INADDR_NONE)
{
    hp=gethostbyname(servername);
}
else
{
    addr=inet_addr(servername);
    hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
    closesocket(conn);
    return;
}

Connecting to the server

The connect() function is used to establish a connection to the destination server. We pass it the socket we created earlier as well as a sockaddr structure. We populate the sockaddr with the host address returned by gethostbyname()/gethostbyaddr(), as well as enter a valid port to connect to.

server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(80);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
    closesocket(conn);
    return;	
}

Chatting

Once the socket connection is established the client and the server can

send() 
and recv() data between themselves. This is popularly referred to as TCP chatting. In our particular case we need to HTTP chat, which is comparatively simple when you consider other slightly more complicated protocols like SMTP or POP3. The HTTP GET command is used to retrieve a file from the HTTP server. This might be an HTML file or an image file or a zip or an MP3 or whatever. It is send thus [in it's simplest form]. There are other slightly more complex ways of using this command.

GET http-path-to-file\r\n\r\n

And in our program we do something like this to send the GET command :-

sprintf(buff,"GET %s\r\n\r\n",filepath);
send(conn,buff,strlen(buff),0);

Once we have send the command we know that the server is going to start sending us the file we just requested. Just as we used send() to send our command we can use recv() to receive the data that the server is going to send us. We loop on recv() till it returns zero when we understand that the server has finished sending us the data. And in our particular case we write all this data to a file as our intention is to download and save a file.

while(y=recv(conn,buff,512,0))
{
    f.Write(buff,y);
}

Close the connection

Now that our chat is over, we must close the connection. In our case the HTTP connection is closed by the server the moment it finishes sending the file, but that doesn't matter. We need to close our socket and release the resource. In more complex chats we usually call shutdown() before we call closesocket() to ensure that the buffers are flushed. Otherwise we might encounter some data loss.

closesocket(conn);

De-Initialize WinSock

We call WSACleanup() to conclude our usage of WinSock.

WSACleanup();

Thank you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
GeneralMy vote of 3 Pin
hoseinhero12-Aug-12 7:49
hoseinhero12-Aug-12 7:49 
Questiongethostbyaddr is unnecessary Pin
tamas.somogyi25-Apr-12 4:54
tamas.somogyi25-Apr-12 4:54 
GeneralMy vote of 3 Pin
enhzflep26-Oct-11 21:34
enhzflep26-Oct-11 21:34 
GeneralMy vote of 5 Pin
Rock Dai14-Aug-10 22:08
Rock Dai14-Aug-10 22:08 
Generalstudy Pin
ycd7-Jun-10 16:42
ycd7-Jun-10 16:42 
Generalnew bgs Pin
cen_jin_long22-Feb-10 12:45
cen_jin_long22-Feb-10 12:45 
Questionwinsock programming for ethernet communication using ADAM 6050 module Pin
mayank17satra4-Nov-09 3:17
mayank17satra4-Nov-09 3:17 
GeneralA Universal C++ TCP Socket Class for Non-blocking Server/Clients Pin
Elmue22-Mar-09 9:08
Elmue22-Mar-09 9:08 
QuestionWhat 's the problem of the send? Anyone know it? Pin
JG.Shi6-Jan-09 21:19
JG.Shi6-Jan-09 21:19 
QuestionConnecting with Hostname to host with Static IP Addresses Pin
ddas-edEn4-Sep-07 1:34
ddas-edEn4-Sep-07 1:34 
GeneralGreat Example Pin
isnainsd20-Aug-07 23:39
isnainsd20-Aug-07 23:39 
Questionwhat if proxy server is used ? Pin
Harviz Harrison25-Apr-07 23:43
Harviz Harrison25-Apr-07 23:43 
Generalsynchronous windows socket Pin
mavsolos11-Apr-07 3:25
mavsolos11-Apr-07 3:25 
Questionhow to implement webserver optimization project codings Pin
ilaiah21-Mar-07 0:16
ilaiah21-Mar-07 0:16 
GeneralRedefinition Error Pin
deepak.cse0710-Feb-07 19:45
deepak.cse0710-Feb-07 19:45 
Generalnew to winsock programming Pin
dhavall8-Sep-06 21:03
dhavall8-Sep-06 21:03 
QuestionHow to do socket and user interface therad in vc++ Pin
sherton30-Jun-06 3:25
sherton30-Jun-06 3:25 
GeneralAdditional information for users Pin
Brit25-Jun-06 16:26
Brit25-Jun-06 16:26 
Generalnot connecting to server Pin
Rakesh K R11-Feb-06 1:24
Rakesh K R11-Feb-06 1:24 
Generalcallback function with winsocks Pin
Amir Ram Shrestha24-Jul-05 19:19
Amir Ram Shrestha24-Jul-05 19:19 
GeneralRegarding SMTP Pin
PoornimaS7-Apr-05 20:43
PoornimaS7-Apr-05 20:43 
GeneralTQConvert in .NET Pin
chal_adiera3-Mar-05 14:38
chal_adiera3-Mar-05 14:38 
Generalclient not receiving Pin
2-Feb-05 21:14
suss2-Feb-05 21:14 
GeneralEthernet Programming Pin
Miekie15-Sep-04 16:58
Miekie15-Sep-04 16:58 
GeneralWinsock Programming Pin
Member 111807723-May-04 21:59
Member 111807723-May-04 21:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.