Click here to Skip to main content
14,544,533 members

Beginning Winsock Programming - Simple TCP server

Rate this:
4.93 (130 votes)
Please Sign up or sign in to vote.
4.93 (130 votes)
25 Feb 2002
An introduction to WinSock programming. A simple TCP server is explained.


The WinSock (Windows Sockets) API is a socket programming library for Microsoft Windows Operating Systems. It was originally based on Berkeley sockets. But several Microsoft specific changes were employed. In this article I shall attempt to introduce you to socket programming using WinSock, assuming that you have never done any kind of network programming on any Operating System.

If you only have a single machine, then don't worry. You can still program WinSock. You can use the local loop-back address called localhost with the IP address Thus if you have a TCP server running on your machine, a client program running on the same machine can connect to the server using this loop-back address.

Simple TCP Server

In this article I introduce you to WinSock through a simple TCP server, which we shall create step by step. But before we begin, there are a few things that you must do, so that we are truly ready for starting our WinSock program

  • Initially use the VC++ 6.0 App Wizard to create a Win32 console application. 
  • Remember to set the option to add support for MFC
  • Open the file stdafx.h and add the following line :- #include <winsock2.h>
  • Also #include conio.h and iostream just after winsock2.h
  • Take Project-Settings-Link and add ws2_32.lib to the library modules list.

The main function

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    int nRetCode = 0;	
    cout << "Press ESCAPE to terminate program\r\n";
    return nRetCode;

What we do in our main() is to start a thread and then loop a call to _getch(). _getch() simply waits till a key is pressed and returns the ASCII value of the character read. We loop till a value of 27 is returned, since 27 is the ASCII code for the ESCAPE key. You might be wondering that even if we press ESCAPE, the thread we started would still be active. Don't worry about that at all. When main() returns the process will terminate and the threads started by our main thread will also be abruptly terminated.

The ServerThread function

What I will do now is to list our ServerThread function and use code comments to explain what each relevant line of code does. Basically what our TCP server does is this. It listens on port 20248, which also happens to be my Code Project membership ID. Talk about coincidences. When a client connects, the server will send back a message to the client giving it's IP address and then close the connection and go back to accepting connections on port 20248. It will also print a line on the console where it's running that there was a connection from this particular IP address. All in all, an absolutely useless program, you might be thinking. In fact some of you might even think this is as useless as SNDREC32.EXE which comes with Windows. Cruel of those people I say.

UINT  ServerThread(LPVOID pParam)
    cout << "Starting up TCP server\r\n";

    //A SOCKET is simply a typedef for an unsigned int.
    //In Unix, socket handles were just about same as file 
    //handles which were again unsigned ints.
    //Since this cannot be entirely true under Windows
    //a new data type called SOCKET was defined.
    SOCKET server;

    //WSADATA is a struct that is filled up by the call 
    //to WSAStartup
    WSADATA wsaData;

    //The sockaddr_in specifies the address of the socket
    //for TCP/IP sockets. Other protocols use similar structures.
    sockaddr_in local;

    //WSAStartup initializes the program for calling WinSock.
    //The first parameter specifies the highest version of the 
    //WinSock specification, the program is allowed to use.
    int wsaret=WSAStartup(0x101,&wsaData);

    //WSAStartup returns zero on success.
    //If it fails we exit.
        return 0;

    //Now we populate the sockaddr_in structure
    local.sin_family=AF_INET; //Address family
    local.sin_addr.s_addr=INADDR_ANY; //Wild card IP address
    local.sin_port=htons((u_short)20248); //port to use

    //the socket function creates our SOCKET

    //If the socket() function fails we exit
        return 0;

    //bind links the socket we just created with the sockaddr_in 
    //structure. Basically it connects the socket with 
    //the local address and a specified port.
    //If it returns non-zero quit, as this indicates error
        return 0;

    //listen instructs the socket to listen for incoming 
    //connections from clients. The second arg is the backlog
        return 0;

    //we will need variables to hold the client socket.
    //thus we declare them here.
    SOCKET client;
    sockaddr_in from;
    int fromlen=sizeof(from);

    while(true)//we are looping endlessly
        char temp[512];

        //accept() will accept an incoming
        //client connection
            (struct sockaddr*)&from,&fromlen);
        sprintf(temp,"Your IP is %s\r\n",inet_ntoa(from.sin_addr));

        //we simply send this string to the client
        cout << "Connection from " << inet_ntoa(from.sin_addr) <<"\r\n";
        //close the client socket


    //closesocket() closes the socket and releases the socket descriptor

    //originally this function probably had some use
    //currently this is just for backward compatibility
    //but it is safer to call it as I still believe some
    //implementations use this to terminate use of WS2_32.DLL 

    return 0;

Testing it out

Run the server and use telnet to connect to port 20248 of the machine where the server is running. If you have it on the same machine connect to localhost.

Sample Output

We see this output on the server

Press ESCAPE to terminate program
Starting up TCP server
Connection from
Connection from

And this is what the client gets

nish@sumida:~$ telnet 20248
Connected to
Escape character is '^]'.
Your IP is
Connection closed by foreign host.


Well, in this article you learned how to create a simple TCP server. In further articles I'll show you more stuff you can do with WinSock including creating a proper TCP client among other things. If anyone has problems with compiling the code, mail me and I shall send you a zipped project. Thank you.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Nish Nishant
United States United States
Nish Nishant is a Principal Software Architect based out of Columbus, Ohio. He has over 17 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish was a Microsoft Visual C++ MVP between 2002 and 2015.

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored C++/CLI in Action for Manning Publications in 2005, and had previously co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on and another 250+ blog articles on his WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : If you are interested in hiring Nish as a consultant, you can reach him via his google email id voidnish.

Company Website :

Comments and Discussions

QuestionRequest to share project file Pin
my_u_name15-Dec-19 17:42
Membermy_u_name15-Dec-19 17:42 
QuestionWhere is AfxBeginThread decleration?? Pin
MA Msh10-Oct-15 4:35
MemberMA Msh10-Oct-15 4:35 
QuestionHello ZipFile needed Pin
dongseopshin3-Jun-14 17:06
Memberdongseopshin3-Jun-14 17:06 
Questionproject code Pin
Member 107891236-May-14 20:12
MemberMember 107891236-May-14 20:12 
QuestionProject code needed Pin
column.column8-Apr-14 21:32
Membercolumn.column8-Apr-14 21:32 
Questionerror in tcp server code Pin
Member 107263495-Apr-14 0:01
MemberMember 107263495-Apr-14 0:01 
QuestionNeed code Pin
chethan.k784516-Jan-14 19:28
Memberchethan.k784516-Jan-14 19:28 
GeneralZipped Project File Pin
Diplomat25-Jul-12 22:53
MemberDiplomat25-Jul-12 22:53 
GeneralMy vote of 5 Pin
Humberto Raposa18-Jun-12 9:10
MemberHumberto Raposa18-Jun-12 9:10 
Questionwaiting for project file Pin
byronli7-Jun-12 15:42
Memberbyronli7-Jun-12 15:42 
Questionsend file to server through http request Pin
ritesh 20106-Mar-12 20:56
Memberritesh 20106-Mar-12 20:56 
QuestionPlease send me the zipped project? Pin
fabmkk12-Feb-12 20:03
Memberfabmkk12-Feb-12 20:03 
QuestionProject File Pin
ikurtoglu19-Jan-12 1:45
Memberikurtoglu19-Jan-12 1:45 
Generalproject file Pin
sheran aus17-Jun-11 20:29
Membersheran aus17-Jun-11 20:29 
Generalproject file Pin
sheran aus17-Jun-11 20:28
Membersheran aus17-Jun-11 20:28 
GeneralCan you send me the project file? Pin
cafukarfoo25-May-11 22:22
Membercafukarfoo25-May-11 22:22 
GeneralMy vote of 5 Pin
zhllq@126.com25-Mar-11 6:49
Memberzhllq@126.com25-Mar-11 6:49 
Generalneed zip file!!! Pin
aarthi krishnan15-Jul-10 2:30
Memberaarthi krishnan15-Jul-10 2:30 
Generalthanks and i Pin
amir farkhondeh27-Jun-10 22:09
Memberamir farkhondeh27-Jun-10 22:09 Pin
neu_lake15-Mar-10 17:26
Memberneu_lake15-Mar-10 17:26 
QuestionError during compiling..... i m using windows Vista Pin
pratikmota4-Feb-10 10:15
Memberpratikmota4-Feb-10 10:15 
QuestionNot able to sniff TCP packet on windows Vista. But could do so on XP Pin
Aseem Sharma21-Dec-09 21:50
MemberAseem Sharma21-Dec-09 21:50 
GeneralWould you please send me a copy of the source code? Thank you a lot! Pin
beyondfe29-Oct-09 17:06
Memberbeyondfe29-Oct-09 17:06 
GeneralI will need the zip file too for this project. Pin
Yogesh Ithape27-Oct-09 2:28
MemberYogesh Ithape27-Oct-09 2:28 
GeneralPlease mail me a project ZIP file Pin
Lintao Wang21-Oct-09 11:45
MemberLintao Wang21-Oct-09 11:45 

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.

Posted 25 Feb 2002


272 bookmarked