Download Winsock Tutorial Socket Programming in C on Windows Binary Tides PDF

TitleWinsock Tutorial Socket Programming in C on Windows Binary Tides
TagsDigital & Social Media Port (Computer Networking) Hypertext Transfer Protocol Digital Technology Network Socket
File Size127.3 KB
Total Pages17
Table of Contents
                            Winsock tutorial – Socket programming in C on windows
	Socket programming with winsock
	Before you begin
	Initialising Winsock
	Creating a socket
	Connect to a Server
	Sending Data
	Receiving Data
	Close socket
	Lets Revise
	Get IP address of a hostname/domain
	Server Concepts
	Bind a socket
	Listen for connections
	Accept connection
	Live Server
	Handling Connections
Document Text Contents
Page 1

Winsock tutorial – Socket programming in C on windows
Socket programming with winsock

This is a quick guide/tutorial to learning socket programming in C language on Windows. "Windows" because
the code snippets shown over here will work only on Windows. The windows api to socket programming is
called winsock.

Sockets are the fundamental "things" behind any kind of network communications done by your computer.
For example when you type in your web browser, it opens a socket and connects to to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network
communication goes through a socket.

Before you begin

This tutorial assumes that you have basic knowledge of C and pointers. Also download Visual C++ 2010 Express

Initialising Winsock

Winsock first needs to be initialiased like this :

winsock2.h is the header file to be included for winsock functions. ws2_32.lib is the library file to be linked with
the program to be able to use winsock functions.

The WSAStartup function is used to start or initialise winsock library. It takes 2 parameters ; the first one is the
version we want to load and second one is a WSADATA structure which will hold additional information after
winsock has been loaded.

If any error occurs then the WSAStartup function would return a non zero value and WSAGetLastError can be
used to get more information about what error happened.

1 /*
2 Initialise Winsock
3 */
5 #include<stdio.h>
6 #include<winsock2.h>
8 #pragma comment(lib,"ws2_32.lib") //Winsock Library

10 intint main(intint argc , charchar *argv[])
11 {
12 WSADATA wsa;
14 printfprintf("\nInitialising Winsock...");
15 ifif (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
16 {
17 printfprintf("Failed. Error Code : %d",WSAGetLastError());
18 returnreturn 1;
19 }
21 printfprintf("Initialised.");
23 returnreturn 0;
24 }

Page 2

OK , so next step is to create a socket.

Creating a socket

The socket() function is used to create a socket.
Here is a code sample :

Function socket() creates a socket and returns a socket descriptor which can be used in other network
commands. The above code will create a socket of :

Address Family : AF_INET (this is IP version 4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Protocol : 0 [ or IPPROTO_TCP , IPPROTO_UDP ]

It would be a good idea to read some documentation here

Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server
using this socket. We can connect to


1 /*
2 Create a TCP socket
3 */
5 #include<stdio.h>
6 #include<winsock2.h>
8 #pragma comment(lib,"ws2_32.lib") //Winsock Library

10 intint main(intint argc , charchar *argv[])
11 {
12 WSADATA wsa;
13 SOCKET s;
15 printfprintf("\nInitialising Winsock...");
16 ifif (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
17 {
18 printfprintf("Failed. Error Code : %d",WSAGetLastError());
19 returnreturn 1;
20 }
22 printfprintf("Initialised.\n");
25 ifif((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
26 {
27 printfprintf("Could not create socket : %d" , WSAGetLastError());
28 }
30 printfprintf("Socket created.\n");
32 returnreturn 0;
33 }

Page 8

Thats it.

Lets Revise

So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply

Its useful to know that your web browser also does the same thing when you open
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch
or retrieve data.

The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming
connections and provide them with data. It is just the opposite of Client. So is a server and
your web browser is a client. Or more technically is a HTTP Server and your web browser is
an HTTP client.

Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that
should be covered just incase you need them.

Get IP address of a hostname/domain

When connecting to a remote host , it is necessary to have its IP address. Function gethostbyname is used for
this purpose. It takes the domain name as the parameter and returns a structure of type hostent. This structure
has the ip information. It is present in netdb.h. Lets have a look at this structure

The h_addr_list has the IP addresses. So now lets have some code to use them.

1 closesocket(s);
2 WSACleanup();

1 /* Description of data base entry for a single host. */
2 structstruct hostent
3 {
4 charchar *h_name; /* Official name of host. */
5 charchar **h_aliases; /* Alias list. */
6 intint h_addrtype; /* Host address type. */
7 intint h_length; /* Length of address. */
8 charchar **h_addr_list; /* List of addresses from name server. */
9 };

1 /*
2 Get IP address from domain name
3 */
5 #include<stdio.h>
6 #include<winsock2.h>
8 #pragma comment(lib,"ws2_32.lib") //Winsock Library

10 intint main(intint argc , charchar *argv[])
11 {
12 WSADATA wsa;
13 charchar *hostname = "";
14 charchar ip[100];
15 structstruct hostent *he;
16 structstruct in_addr **addr_list;

Page 9

Output of the code would look like :

So the above code can be used to find the ip address of any domain name. Then the ip address can be used to
make a connection using a socket.

Function inet_ntoa will convert an IP address in long format to dotted format. This is just the opposite of

So far we have see some important structures that are used. Lets revise them :

1. sockaddr_in - Connection information. Used by connect , send , recv etc.
2. in_addr - Ip address in long format
3. sockaddr
4. hostent - The ip addresses of a hostname. Used by gethostbyname

Server Concepts

OK now onto server things. Servers basically do the following :

1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send

17 intint i;
19 printfprintf("\nInitialising Winsock...");
20 ifif (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
21 {
22 printfprintf("Failed. Error Code : %d",WSAGetLastError());
23 returnreturn 1;
24 }
26 printfprintf("Initialised.\n");
29 ifif ( (he = gethostbyname( hostname ) ) == NULL)
30 {
31 //gethostbyname failed
32 printfprintf("gethostbyname failed : %d" , WSAGetLastError());
33 returnreturn 1;
34 }
36 //Cast the h_addr_list to in_addr , since h_addr_list also has the ip

address in long format only
37 addr_list = (structstruct in_addr **) he->h_addr_list;
39 forfor(i = 0; addr_list[i] != NULL; i++)
40 {
41 //Return the first one;
42 strcpystrcpy(ip , inet_ntoa(*addr_list[i]) );
43 }
45 printfprintf("%s resolved to : %s\n" , hostname , ip);
46 returnreturn 0;
47 returnreturn 0;
48 }

1 resolved to :

Page 16

And the server terminal would show

So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the
server program.
All telnet terminals would show "Connection to host lost."
Good so far. But still there is not effective communication between the server and the client.

The server program accepts connections in a loop and just send them a reply, after that it does nothing with
them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections
, and handle multiple connections together.

Handling Connections

To handle every connection we need a separate handling code to run along with the main server accepting
One way to achieve this is using threads. The main server program accepts a connection and creates a
new thread to handle communication for the connection, and then the server goes back to accept more

We shall now use threads to create handlers for each connection the server accepts. Lets do it pal.

Run the above server and open 3 terminals like before. Now the server will create a thread for each client
connecting to it.

The telnet terminals would show :

This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It
should stay alive and keep communicating with the client.

One way to do this is by making the connection handler wait for some message from a client as long as the
client is connected. If the client disconnects , the connection handler ends.

So the connection handler can be rewritten like this :

The above connection handler takes some input from the client and replies back with the same. Simple! Here
is how the telnet output might look

1 C:\>telnet

1 Welcome to Microsoft Telnet Client
2 Escape Character is 'CTRL+]'
3 Microsoft Telnet> open localhost 8888

1 Hello Client , I have received your connection. But I have to go now, bye

1 Initialising Winsock...Initialised.
2 Socket created.
3 Bind donedone
4 Waiting forfor incoming connections...
5 Connection accepted
6 Connection accepted





Page 17

So now we have a server thats communicative. Thats useful now.


The winsock api is quite similar to Linux sockets in terms of function name and structures. Few differences exist
like :

1. Winsock needs to be initialised with the WSAStartup function. No such thing in linux.

2. Header file names are different. Winsock needs winsock2.h , whereas Linux needs socket.h , apra/inet.h ,
unistd.h and many others.

3. Winsock function to close a socket is closesocket , whereas on Linux it is close.
On Winsock WSACleanup must also be called to unload the winsock dll.

4. On winsock the error number is fetched by the function WSAGetLastError(). On Linux the errno variable
from errno.h file is filled with the error number.

And there are many more differences as we go deep.

By now you must have learned the basics of socket programming in C. You can try out some experiments like
writing a chat client or something similar.

If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work
then feel free to make a comment below so that it gets fixed.

Similer Documents