Click here to Skip to main content
14,271,828 members

Server Client Sockets

Rate this:
4.74 (81 votes)
Please Sign up or sign in to vote.
4.74 (81 votes)
25 Apr 2003
Sample application Uses Server and client socket to establish exchange of data


The reason why I decided to write this article is because, I was learning myself how to use sockets under windows, I could not find one place that had a tutorial which included everything I was looking for, or if it did it was way too complicated for me to understand. In the end after doing my research, I put together my resources and came up with this tutorial. I hope that it is clear and informative so that other people can benefit from it.

This article can be divided into 3 sections:

  • Part 1 - Create a server socket that listens for a client to connect
  • Part 2 - Send / receive data from client to server
  • Part 3 - Read unknown size of data from client

Part 1 - Creating a Listening Socket

To use WinSock before we start writing any code, we must include the wsock32.lib and include the:

#pragma comment(lib, "wsock32.lib")

Normally, a socket that waits for a connection is a server, Once the connection has been made, it can spawn off a new Thread to deal with that connection.

Before going into the actual code, let's have a look at some struct we will need to set up a socket:


Any code that is compiled using a winsock accesses the ws2_32.dll and this struct is used during the process of doing so. The program MUST call WSAstartup to initialise the DLL for later use.


This is used to specify how the socket is used and contains the field for the IP and port.


This is an object that stores a handle to the socket

Key Functions to Create the Listening Server Socket

WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData )

This function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets API required and to retrieve details of the specific Windows Sockets implementation. The application or DLL may only issue further Windows Sockets API functions after a successful WSAStartup invocation.

socket(int af, int type, int protocol)

This method creates the socket:

bind(SOCKET s, const struct sockaddr FAR * name, int namelen)

Associates a local address with a socket This routine is used on an unconnected datagram or stream socket, before subsequent connects or listens. When a socket is created with socket, it exists in a name space (address family), but it has no name assigned. bind establishes the local association (host address/port number) of the socket by assigning a local name to an unnamed socket. In the Internet address family, a name consists of several components. For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts: a host address, the protocol number (set implicitly to UDP or TCP, respectively), and a port number which identifies the application. If an application does not care what address is assigned to it, it may specify an Internet address equal to INADDR_ANY, a port equal to 0, or both. If the Internet address is equal to INADDR_ANY, any appropriate network interface will be used; this simplifies application programming in the presence of multi- homed hosts. If the port is specified as 0, the Windows Sockets implementation will assign a unique port to the application with a value between 1024 and 5000. The application may use getsockname after bind to learn the address that has been assigned to it, but note that getsockname will not necessarily fill in the Internet address until the socket is connected, since several Internet addresses may be valid if the host is multi-homed. If no error occurs, bind returns 0. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError.

listen(SOCKET s, int backlog )

Establishes a socket to listen to an incoming connection To accept connections, a socket is first created with socket, a backlog for incoming connections is specified with listen, and then the connections are accepted with accept. listen applies only to sockets that support connections, i.e., those of type SOCK_STREAM. The socket s is put into "passive'' mode where incoming connections are acknowledged and queued pending acceptance by the process. This function is typically used by servers that could have more than one connection request at a time: if a connection request arrives with the queue full, the client will receive an error with an indication of WSAECONNREFUSED. listen attempts to continue to function rationally when there are no available descriptors. It will accept connections until the queue is emptied. If descriptors become available, a later call to listen or accept will re-fill the queue to the current or most recent "backlog'', if possible, and resume listening for incoming connections.

accept(SOCKET s, struct sockaddr FAR * addr, int FAR * addrlen)

This routine extracts the first connection on the queue of pending connections on s, creates a new socket with the same properties as s and returns a handle to the new socket. If no pending connections are present on the queue, and the socket is not marked as non- blocking, accept blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue, accept returns an error as described below. The accepted socket may not be used to accept more connections. The original socket remains open. The argument addr is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family in which the communication is occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. This call is used with connection-based socket types such as SOCK_STREAM. If addr and/or addrlen are equal to NULL, then no information about the remote address of the accepted socket is returned.

closesocket(SOCKET s)

closes a socket.


ends the use of the Windows Sockets DLL.

Example Program

#include <stdio.h>
#include <winsock.h>
#include <windows.h>

#define SOCKET_OK 0

#pragma comment(lib, "wsock32.lib")

void socketError(char*);

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, 
                    LPSTR lpCmdLine, int nShow)
    WORD sockVersion;
    WSADATA wsaData;
    int rVal;

    sockVersion = MAKEWORD(1,1);
    //start dll
    WSAStartup(sockVersion, &wsaData);

    //create socket

    if(s == INVALID_SOCKET)
        socketError("Failed socket()");
        return SERVER_SOCKET_ERROR;

    //fill in sockaddr_in struct 

    SOCKADDR_IN sin;
    sin.sin_family = PF_INET;
    sin.sin_port = htons(8888);
    sin.sin_addr.s_addr = INADDR_ANY;

    //bind the socket
    rVal = bind(s, (LPSOCKADDR)&sin, sizeof(sin));
    if(rVal == SOCKET_ERROR)
        socketError("Failed bind()");
        return SERVER_SOCKET_ERROR;

    //get socket to listen 
    rVal = listen(s, 2);
    if(rVal == SOCKET_ERROR)
        socketError("Failed listen()");
        return SERVER_SOCKET_ERROR;

    //wait for a client
    SOCKET client;

    client = accept(s, NULL, NULL);

    if(client == INVALID_SOCKET)
        socketError("Failed accept()");
        return SERVER_SOCKET_ERROR;

    //close process


    return SOCKET_OK;

void socketError(char* str)
    MessageBox(NULL, str, "SOCKET ERROR", MB_OK);

Making Client Connection with Server

In order to create a socket that connects to another socket uses most of the functions from the previous code with the exception of a struct called HOSTENT.


This struct is used to tell the socket to which computer and port to connect to. These structs can appear as LPHOSTENT, but it actually means that they are pointer to HOSTENT.

Client Key Function

Most of the functions that have been used for the client to connect to the server are the same as the server with the exception of a few. I will just go through the different functions that have been used for the client.

gethostbyname(const char* FAR name)

gethostbyname returns a pointer to a hostent structure as described under gethostbyaddr. The contents of this structure correspond to the hostname name. The pointer which is returned points to a structure which is allocated by the Windows Sockets implementation. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information which it needs before issuing any other Windows Sockets API calls. A gethostbyname implementation must not resolve IP address strings passed to it. Such a request should be treated exactly as if an unknown host name were passed. An application with an IP address string to resolve should use inet_addr to convert the string to an IP address, then gethostbyaddr to obtain the hostent structure.

Example Code

#include <windows.h>
#include <winsock.h>

#pragma comment(lib, "wsock32.lib")

#define CS_ERROR 1
#define CS_OK 0

void sError(char*);

int WINAPI WinMain(HINSTANCE hHinst, HINSTANCE hPrevHinst, LPSTR lpCmdLine, 
                   int nShow)
    WORD version;
    WSADATA wsaData;
    int rVal=0;

    version = MAKEWORD(1,1);


    LPHOSTENT hostEntry;

    //store information about the server
    hostEntry = gethostbyname("hibbert");

        sError("Failed gethostbyname()");
        return CS_ERROR;

    //create the socket

    if(theSocket == SOCKET_ERROR)
        sError("Failed socket()");
        return CS_ERROR;

    //Fill in the sockaddr_in struct
    SOCKADDR_IN serverInfo;

    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);

    serverInfo.sin_port = htons(8888);

    rVal=connect(theSocket,(LPSOCKADDR)&serverInfo, sizeof(serverInfo));
        sError("Failed connect()");
        return CS_ERROR;

    MessageBox(NULL, "Connection was made", "SOCKET", MB_OK);
    return CS_OK;

void sError(char *str)
    MessageBox(NULL, str, "SOCKET ERROR", MB_OK);

Part 2 - Send / Receive

Up to this point, we have managed to connect with our client to the server. Clearly, this is not going to be enough in a real-life application. In this section, we are going to look into more details how to use the send/recv functions in order to get some communication going between the two applications.

Factually, this is not going to be difficult because most of the hard work has been done setting up the server and the client app. Before going into the code, we are going to look into more details of the two functions:

send(SOCKET s, const char FAR * buf, int len, int flags)

send is used on connected datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSAData structure returned by WSAStartup. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.

recv(SOCKET s, const char FAR * buf, int len, int flags)

For sockets of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in- line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application may use the ioctlsocket SIOCATMARK to determine whether any more out-of-band data remains to be read.

Code Example

The following code example demonstrates how to make use of the recv function. The recv function is used after the accept function, and the socket must be connected in order to receive the data.

client = accept(s, NULL, NULL);

cout << "newclient found" << endl;

if(client == INVALID_SOCKET)
    socketError("Failed accept()");

char buf[4];
rVal = recv(client, buf, 4, 0);

if(rVal == SOCKET_ERROR)
    int val = WSAGetLastError();
    if(val == WSAENOTCONN)
        cout << "socket not connected" << endl;
    else if(val == WSAESHUTDOWN )
        cout << "socket has been shut down!" << endl;
    socketError("Failed recv()");

cout << buf << endl;

This code example below works fine when you know exactly how much data you are about to receive. The problem comes when you do not know how much data will arrive. For now we will ignore this problem because the aim here is actually to prove that data has been received. In the next section, we will evolve the way we receive data.

Now we are going to look at how to implement the send function. In actual fact, it is the reverse of receiving data!

rVal=connect(theSocket,(LPSOCKADDR)&serverInfo, sizeof(serverInfo));

    sError("Failed connect()");
    return CS_ERROR;

char *buf = "data";

rVal = send(theSocket, buf, strlen(buf), 0);

if(rVal == SOCKET_ERROR)
    sError("Failed send()");
    return CS_ERROR;

Part 3 - Read Unknown Size of Data from Client

As mentioned earlier in part 2, we are now going to expand on the way that we receive data. The problem we had before is that if we did not know the size of data that we were expecting, then we would end up with problems.

In order to fix this, here we create a new function that receives a pointer to the client socket, and then read a char at the time, placing each char into a vector until we find the '\n' character that signifies the end of the message.

This solution is clearly not a robust or industrial way that read data from one socket to an other, but it's a way to start reading unknown length strings. the function will be called after the accept method.

char * readline(SOCKET *client)
    vector<char> theVector;
    char buffer;
    int rVal;

        rVal = recv(*(client), &buffer, 1, 0);
        if(rVal == SOCKET_ERROR)
            int errorVal = WSAGetLastError();

            if(errorVal == WSAENOTCONN)
                socketError("Socket not connected!");
            socketError("Failed recv()");
        if(buffer == '\n')
            char *data = new char[theVector.size() + 1];
            memset(data, 0, theVector.size()+1);
            for(int i=0; i<theVector.size(); i+=1)
                data[i] = theVector[i];

            cout << data << endl;
            return data;

As we can see, this is a simple and rudimentary way to read a line, we can increase its functionality adding support for \b, \r, \0, and others depending on what the need is.


I hope this tutorial has been of some use, even if the code implementation is fairly simple, it might be of help to further develop programs that need to implement the socket API.

There are many more things to consider when developing with sockets, i.e., NON-Blocking and Asynchronous Socket. I intend to write some more regarding the above topics mentioned as they are very important for more robust and industrial programs.


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

Web Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

Questionaa Pin
Member 1063169828-Apr-15 0:50
memberMember 1063169828-Apr-15 0:50 
Questionwhy getaddrinfo(pstrHost, pstrService, &aiHints, &aiList) ) return -2 Pin
ronaldohf22-Apr-12 22:33
memberronaldohf22-Apr-12 22:33 
AnswerRe: why getaddrinfo(pstrHost, pstrService, &aiHints, &aiList) ) return -2 Pin
Emiliano30-Apr-12 7:27
memberEmiliano30-Apr-12 7:27 
GeneralMy vote of 5 Pin
raindropb_boy25-Dec-10 18:34
memberraindropb_boy25-Dec-10 18:34 
GeneralJust for thanking you Pin
Mingyang Yu13-Jun-10 1:59
memberMingyang Yu13-Jun-10 1:59 
Generalthanks man Pin
mohammadzeyad17-Aug-09 10:17
membermohammadzeyad17-Aug-09 10:17 
General[Message Deleted] Pin
it.ragester2-Apr-09 21:41
memberit.ragester2-Apr-09 21:41 
Generalthere's an accident in server_part2.cpp Pin
bobdolebananaphone219-Oct-08 13:24
memberbobdolebananaphone219-Oct-08 13:24 
Generalideal to start socket programming... Pin
Nitin Karmarkar19-May-08 23:35
memberNitin Karmarkar19-May-08 23:35 
GeneralIf i want to send and receive a web page using your code Pin
kansagous21-Nov-07 20:32
memberkansagous21-Nov-07 20:32 
Generaludp client-server Pin
melfice8219-Nov-07 19:33
membermelfice8219-Nov-07 19:33 
Generalclient/server program in c (windows) Pin
nsaffar5-Nov-07 0:03
membernsaffar5-Nov-07 0:03 
Generalserver port advertising strategies Pin
grgavinr24-Oct-07 10:37
membergrgavinr24-Oct-07 10:37 
GeneralRe: server port advertising strategies Pin
Emiliano25-Oct-07 0:46
memberEmiliano25-Oct-07 0:46 
GeneralRe: server port advertising strategies Pin
grgavinr25-Oct-07 11:18
membergrgavinr25-Oct-07 11:18 
GeneralRe: server port advertising strategies Pin
Iswarya Devi29-Oct-07 4:08
memberIswarya Devi29-Oct-07 4:08 
GeneralServer is recieving incorrect data Pin
Ms. Agrawal24-May-07 19:11
memberMs. Agrawal24-May-07 19:11 version of the code sample Pin
travis_1121121419-May-07 23:46
membertravis_1121121419-May-07 23:46 
Generalsending image synchronizingly Pin
mavsolos14-Apr-07 10:48
membermavsolos14-Apr-07 10:48 
Generalsending bitmap file using this code Pin
mavsolos15-Feb-07 1:37
membermavsolos15-Feb-07 1:37 
GeneralRe: sending bitmap file using this code Pin
john_17269-May-07 16:24
memberjohn_17269-May-07 16:24 
GeneralRe: eror part Pin
_KD_23-Jan-07 5:52
member_KD_23-Jan-07 5:52 
GeneralFailed gethostbyname() Pin
ashwag1-Nov-06 8:01
memberashwag1-Nov-06 8:01 
GeneralRe: Failed gethostbyname() Pin
john_17269-May-07 16:21
memberjohn_17269-May-07 16:21 
Generalproblems on Vc6 Pin
raggnar23-Sep-06 15:37
memberraggnar23-Sep-06 15:37 

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 Apr 2003


189 bookmarked