An Intro to Windows Socket (Winsock2) Programming 10

 

 

 

 

 

Client Program Example

 

The following program example demonstrates how to write a simple client that can connect to the server application demonstrated earlier.

 

1.   While in the Visual C++ IDE, click File menu > Project sub menu to create a new project.

2.   Select Win32 for the Project types: and Win32 Console Application for the Templates:. Put the project and solution name. Adjust the project location if needed and click OK.

 

Windows Socket (Winsock2) Programming and  C Language: creating new C Win32 console application

 

3.   Click Next for the Win32 Application Wizard Overview page. We will remove all the unnecessary project items.

4.   In the Application page, select Empty project for the Additional options:. Leave others as given and click Finish.

 

Windows Socket (Winsock2) Programming and  C Language: selecting an empty Win32 console application

 

5.   Next, we need to add new source file. Click Project menu > Add New Item sub menu or select the project folder in the Solution Explorer > Select Add menu > Select New Item sub menu.

6.   Select C++ File (.cpp) for the Templates:. Put the source file name and click Add. Although the extension is .cpp, Visual C++ IDE will recognize that the source code used is C based on the Compile as C Code (/TC) option which will be set in the project property page later.

 

Windows Socket (Winsock2) Programming and  C Language: adding a C source file to the existing project

 

7.   Now, add the source code as given below.

 

#include <winsock2.h>

#include <stdio.h>

 

int main(int argc, char **argv)

{

            WSADATA              wsaData;

            SOCKET               SendingSocket;

            // Server/receiver address

            SOCKADDR_IN          ServerAddr;

            // Server/receiver port to connect to

            unsigned int         Port = 80;

            int        RetCode;

 

            // Initialize Winsock version 2.2

            WSAStartup(MAKEWORD(2,2), &wsaData);

            printf("Client: Winsock DLL status is %s.\n", wsaData.szSystemStatus);

           

            // Create a new socket to make a client connection.

            // AF_INET = 2, The Internet Protocol version 4 (IPv4) address family, TCP protocol

            SendingSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

            if(SendingSocket == INVALID_SOCKET)

            {

                        printf("Client: socket() failed! Error code: %ld\n", WSAGetLastError());

                        // Do the clean up

                        WSACleanup();

                        // Exit with error

                        return -1;

            }

            else

                        printf("Client: socket() is OK!\n");    

           

            // Set up a SOCKADDR_IN structure that will be used to connect

            // to a listening server on port 5150. For demonstration

            // purposes, let's assume our server's IP address is 127.0.0.1 or localhost

 

            // IPv4

            ServerAddr.sin_family = AF_INET;

            // Port no.

            ServerAddr.sin_port = htons(Port);

            // The IP address

            ServerAddr.sin_addr.s_addr = inet_addr("209.131.36.158");

           

            // Make a connection to the server with socket SendingSocket.

            RetCode = connect(SendingSocket, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr));

            if(RetCode != 0)

            {

                        printf("Client: connect() failed! Error code: %ld\n", WSAGetLastError());

                        // Close the socket

                        closesocket(SendingSocket);

                        // Do the clean up

                        WSACleanup();

                        // Exit with error

                        return -1;

            }

            else

            {

                        printf("Client: connect() is OK, got connected...\n");

                        printf("Client: Ready for sending and receiving data...\n");

            }

           

            // At this point you can start sending or receiving data on

            // the socket SendingSocket. We will describe sending and receiving data later in the chapter.

 

            // When you are finished sending and receiving data on socket SendingSocket,

            // you should close the socket using the closesocket API. We will describe socket closure later in the chapter.

            if(closesocket(SendingSocket) != 0)

                        printf("Client: Cannot close \"SendingSocket\" socket. Error code: %ld\n", WSAGetLastError());

            else

                        printf("Client: Closing \"SendingSocket\" socket...\n");

 

            // When your application is finished handling the connection, call WSACleanup().

            if(WSACleanup() != 0)

                        printf("Client: WSACleanup() failed!...\n");

            else

                        printf("Client: WSACleanup() is OK...\n");

            return 0;

}

 

8.   In the meantime, if you want to enable the line number for the VC++ editor, invoke the project Options page.

 

Windows Socket (Winsock2) Programming and  C Language: invoking the Visual C++ Options project page menu

 

9.   Expand the Text Editor folder > Select C/C++ link > Check the Line numbers option in the Display checkbox group.

 

Windows Socket (Winsock2) Programming and  C Language: enabling the Visual C++ editor line number

 

10.  Then, build the project and make sure there is no error.

 

Windows Socket (Winsock2) Programming and  C Language: building C Winsock2 project

 

11.  Run the project.

 

Windows Socket (Winsock2) Programming and  C Language: running the C Winsock2 project without debugging

 

12.  If there is no error, the following sample output should be expected.

 

Windows Socket (Winsock2) Programming and  C Language: a sample of Winsock2 client console output with connection refused error code

 

13.The error code 10061 is enumeration for WSAECONNREFUSED which is a Connection refused. It is because there is no listening server on the specified address and port number. The next steps will demonstrate the client and server programs running.

14.Run the previous server program from command prompt (or you can open another Visual C++ IDE instance and run it).

 

Windows Socket (Winsock2) Programming and  C Language: the Winsock server/receiver in action, ready to accept connection from clients

 

15.  Then, run the client program. The following screenshot shows the client-server communication.

 

Windows Socket (Winsock2) Programming and  C Language: the Winsock2 server/receiver and client/sender in actions

 

16. Next, let test this client connection to the real server. In this case we change the port to 80 (standard http port) and the server is www.yahoo.com or www.google.com. Then we rebuild the project. You can use the ping tool to get the server address.

 

Windows Socket (Winsock2) Programming and  C Language: running the ping command against domain name to get the IP address

 

17.  The following screenshot shows a sample output when connecting to one of the Yahoo.com web server.

 

Windows Socket (Winsock2) Programming and  C Language: testing the client/sender program against the real server

 

Now that you can set up communication for a connection-oriented server and client, you are ready to begin handling data transmission.

 

 

 

 

< Winsock2 9 | Windows Socket 2 (Winssock2) | Win32 Programming | Winsock2 11 >