Winsock Socket Programming in C On Windows
Winsock Socket Programming in C On Windows
Initialising Winsock
1
2
3 /*
4 Initialise Winsock
5 */
6 #include<stdio.h>
7 #include<winsock2.h>
8 #pragma comment(lib,"ws2_32.lib") //Winsock Library
9 int main(int argc , char *argv[])
10{
11 WSADATA wsa;
12
13 printf("\nInitialising Winsock...");
14 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
15 {
16 printf("Failed. Error Code : %d",WSAGetLastError());
17 return 1;
18 }
19
20 printf("Initialised.");
21 return 0;
22}
23
24
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.
Creating a socket
1
2
3
/*
4
Create a TCP socket
5
*/
6
#include<stdio.h>
7
#include<winsock2.h>
8
#pragma comment(lib,"ws2_32.lib") //Winsock Library
9
int main(int argc , char *argv[])
10
{
11
WSADATA wsa;
12
SOCKET s;
13
printf("\nInitialising Winsock...");
14
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
15
{
16
printf("Failed. Error Code : %d",WSAGetLastError());
17
return 1;
18
}
19
20
printf("Initialised.\n");
21
22
23
if((s = socket(AF_INET , SOCK_STREAM , 0 )) ==
24
INVALID_SOCKET)
25
{
26
printf("Could not create socket : %d" , WSAGetLastError());
27
}
28
printf("Socket created.\n");
29
return 0;
30
}
31
32
33
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 :
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 http://www.google.com
Note
Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates
the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to
SOCK_STREAM or TCP sockets.
Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port
number to connect to.
To connect to a remote server we need to do a couple of things. First is create a sockaddr_in structure
with proper values filled in. Lets create one for ourselves :
The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a
long. It contains the IP address in long format.
Function inet_addr is a very handy function to convert an IP address to a long format. This is how you do
it :
1server.sin_addr.s_addr = inet_addr("74.125.235.20");
So you need to know the IP address of the remote server you are connecting to. Here we used the ip
address of google.com as a sample. A little later on we shall see how to find out the ip address of a given
domain name.
The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to.
Here is a code sample.
1 /*
2 Create a TCP socket
3 */
4 #include<stdio.h>
5 #include<winsock2.h>
6 #pragma comment(lib,"ws2_32.lib") //Winsock Library
7 int main(int argc , char *argv[])
8 {
9 WSADATA wsa;
10 SOCKET s;
11 struct sockaddr_in server;
12 printf("\nInitialising Winsock...");
13 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
14 {
15 printf("Failed. Error Code : %d",WSAGetLastError());
16 return 1;
17 }
18
19 printf("Initialised.\n");
20
21 //Create a socket
22 if((s = socket(AF_INET , SOCK_STREAM , 0 )) ==
23 INVALID_SOCKET)
24 {
25 printf("Could not create socket : %d" , WSAGetLastError());
26 }
27 printf("Socket created.\n");
28
29
30 server.sin_addr.s_addr = inet_addr("74.125.235.20");
31 server.sin_family = AF_INET;
32 server.sin_port = htons( 80 );
33 //Connect to remote server
34 if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
35 {
36 puts("connect error");
37 return 1;
38 }
39
40 puts("Connected");
41 return 0;
42 }
43
44
45
46
47
48
It cannot be any simpler. It creates a socket and then connects. If you run the program it should show
Connected.
Try connecting to a port different from port 80 and you should not be able to connect which indicates that
the port is not open for connection.
OK , so we are now connected. Lets do the next thing , sending some data to the remote server.
Quick Note
Other sockets like UDP , ICMP , ARP dont have a concept of “connection”. These are non-connection
based communication. Which means you keep sending or receiving packets from anybody and
everybody.
Sending Data
Function send will simply send data. It needs the socket descriptor , the data to send and its size.
Here is a very simple example of sending some data to google.com ip :
1 /*
2 Create a TCP socket
3 */
4 #include<stdio.h>
5 #include<winsock2.h>
6 #pragma comment(lib,"ws2_32.lib") //Winsock Library
7 int main(int argc , char *argv[])
8 {
9 WSADATA wsa;
10 SOCKET s;
11 struct sockaddr_in server;
12 char *message;
13 printf("\nInitialising Winsock...");
14 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
15 {
16 printf("Failed. Error Code : %d",WSAGetLastError());
17 return 1;
18 }
19
20 printf("Initialised.\n");
21
22 //Create a socket
23 if((s = socket(AF_INET , SOCK_STREAM , 0 )) ==
24 INVALID_SOCKET)
25 {
26 printf("Could not create socket : %d" , WSAGetLastError());
27 }
28 printf("Socket created.\n");
29
30
31 server.sin_addr.s_addr = inet_addr("74.125.235.20");
32 server.sin_family = AF_INET;
33 server.sin_port = htons( 80 );
34 //Connect to remote server
35 if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
36 {
37 puts("connect error");
38 return 1;
39 }
40
41 puts("Connected");
42
43 //Send some data
44 message = "GET / HTTP/1.1\r\n\r\n";
45 if( send(s , message , strlen(message) , 0) < 0)
46 {
47 puts("Send failed");
48 return 1;
49 }
50 puts("Data Send\n");
51 return 0;
52 }
53
54
55
56
57
58
In the above example , we first connect to an ip address and then send the string message “GET /
HTTP/1.1\r\n\r\n” to it.
The message is actually a http command to fetch the mainpage of a website.
Now that we have send some data , its time to receive a reply from the server. So lets do it.
Receiving Data
Function recv is used to receive data on a socket. In the following example we shall send the same
message as the last example and receive a reply from the server.
/*
Create a TCP socket
*/
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message , server_reply[2000];
int recv_size;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("74.125.235.20");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
//Connect to remote server
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com
(NOTE: if google change ip use “ping google.com” in cmd to retreived their IP) replied with the
content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.
Close socket
Function closesocket is used to close the socket. Also WSACleanup must be called to unload the winsock
library (ws2_32.dll).
1closesocket(s);
2WSACleanup();
Thats it.
LETS REVISE
Its useful to know that your web browser also does the same thing when you open http://www.google.com
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
http://www.google.com is a server and your web browser is a client. Or more technically
http://www.google.com 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.
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 /*
2 Get IP address from domain name
3 */
4 #include<stdio.h>
5 #include<winsock2.h>
6 #pragma comment(lib,"ws2_32.lib") //Winsock Library
7 int main(int argc , char *argv[])
8 {
9 WSADATA wsa;
10 char *hostname = "www.google.com";
11 char ip[100];
12 struct hostent *he;
13 struct in_addr **addr_list;
14 int i;
15
16 printf("\nInitialising Winsock...");
17 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
18 {
19 printf("Failed. Error Code : %d",WSAGetLastError());
20 return 1;
21 }
22
23 printf("Initialised.\n");
24
25
26 if ( (he = gethostbyname( hostname ) ) == NULL)
27 {
28 //gethostbyname failed
29 printf("gethostbyname failed : %d" , WSAGetLastError());
30 return 1;
31 }
32
33 //Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only
34 addr_list = (struct in_addr **) he->h_addr_list;
35
36 for(i = 0; addr_list[i] != NULL; i++)
37 {
38 //Return the first one;
39 strcpy(ip , inet_ntoa(*addr_list[i]) );
40 }
41
42 printf("%s resolved to : %s\n" , hostname , ip);
43 return 0;
44 return 0;
45}
46
47
48
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
ofinet_addr.
So far we have see some important structures that are used. Lets revise them :
1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
Bind a socket
Function bind can be used to bind a socket to a particular address and port. It needs a sockaddr_in
structure similar to connect function.
1 /*
2 Bind socket to port 8888 on localhost
3 */
4 #include<stdio.h>
5 #include<winsock2.h>
6 #pragma comment(lib,"ws2_32.lib") //Winsock Library
7 int main(int argc , char *argv[])
8 {
9 WSADATA wsa;
10 SOCKET s;
11 struct sockaddr_in server;
12 printf("\nInitialising Winsock...");
13 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
14 {
15 printf("Failed. Error Code : %d",WSAGetLastError());
16 return 1;
17 }
18
19 printf("Initialised.\n");
20
21 //Create a socket
22 if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
23 {
24 printf("Could not create socket : %d" , WSAGetLastError());
25 }
26 printf("Socket created.\n");
27
28 //Prepare the sockaddr_in structure
29 server.sin_family = AF_INET;
30 server.sin_addr.s_addr = INADDR_ANY;
31 server.sin_port = htons( 8888 );
32
33 //Bind
34 if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
35 {
36 printf("Bind failed with error code : %d" , WSAGetLastError());
37 }
38
39 puts("Bind done");
40
41 closesocket(s);
42 return 0;
43}
44
45
46
47
48
49
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular
IP address and a certain port number. By doing this we ensure that all incoming data which is directed
towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port.
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to
put the socket in listening mode. Function listen is used to put the socket in listening mode. Just add the
following line after bind.
1//Listen
2listen(s , 3);
Thats all. Now comes the main part of accepting new connections.
Accept connection
1 /*
2 Bind socket to port 8888 on localhost
3 */
4 #include<stdio.h>
5 #include<winsock2.h>
6 #pragma comment(lib,"ws2_32.lib") //Winsock Library
7 int main(int argc , char *argv[])
8 {
9 WSADATA wsa;
10 SOCKET s , new_socket;
11 struct sockaddr_in server , client;
12 int c;
13 printf("\nInitialising Winsock...");
14 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
15 {
16 printf("Failed. Error Code : %d",WSAGetLastError());
17 return 1;
18 }
19
20 printf("Initialised.\n");
21
22 //Create a socket
23 if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
24 {
25 printf("Could not create socket : %d" , WSAGetLastError());
26 }
27 printf("Socket created.\n");
28
29 //Prepare the sockaddr_in structure
30 server.sin_family = AF_INET;
31 server.sin_addr.s_addr = INADDR_ANY;
32 server.sin_port = htons( 8888 );
33
34 //Bind
35 if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
36 {
37 printf("Bind failed with error code : %d" , WSAGetLastError());
38 }
39
40 puts("Bind done");
41
42 //Listen to incoming connections
43 listen(s , 3);
44
45 //Accept and incoming connection
46 puts("Waiting for incoming connections...");
47
48 c = sizeof(struct sockaddr_in);
49 new_socket = accept(s , (struct sockaddr *)&client, &c);
50 if (new_socket == INVALID_SOCKET)
51 {
52 printf("accept failed with error code : %d" , WSAGetLastError());
53 }
54
55 puts("Connection accepted");
56 closesocket(s);
57 WSACleanup();
58 return 0;
59}
60
61
62
63
64
65
66
67
Output
1Initialising Winsock...Initialised.
2Socket created.
3Bind done
4Waiting for incoming connections...
So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it
running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal
and type
1Initialising Winsock...Initialised.
2Socket created.
3Bind done
4Waiting for incoming connections...
5Connection accepted
6Press any key to continue
So we can see that the client connected to the server. Try the above process till you get it perfect.
Note
You can get the ip address of client and the port of connection by using the sockaddr_in structure passed
to accept function. It is very simple :
We accepted an incoming connection but closed it immediately. This was not very productive. There are
lots of things that can be done after an incoming connection is established. Afterall the connection was
established for the purpose of communication. So lets reply to the client.
Here is an example :
1 /*
2 Bind socket to port 8888 on localhost
3 */
4 #include<io.h>
5 #include<stdio.h>
6 #include<winsock2.h>
7 #pragma comment(lib,"ws2_32.lib") //Winsock Library
8 int main(int argc , char *argv[])
9 {
10 WSADATA wsa;
11 SOCKET s , new_socket;
12 struct sockaddr_in server , client;
13 int c;
14 char *message;
15 printf("\nInitialising Winsock...");
16 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
17 {
18 printf("Failed. Error Code : %d",WSAGetLastError());
19 return 1;
20 }
21
22 printf("Initialised.\n");
23
24 //Create a socket
25 if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
26 {
27 printf("Could not create socket : %d" , WSAGetLastError());
28 }
29 printf("Socket created.\n");
30
31 //Prepare the sockaddr_in structure
32 server.sin_family = AF_INET;
33 server.sin_addr.s_addr = INADDR_ANY;
34 server.sin_port = htons( 8888 );
35
36 //Bind
37 if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
38 {
39 printf("Bind failed with error code : %d" , WSAGetLastError());
40 }
41
42 puts("Bind done");
43 //Listen to incoming connections
44 listen(s , 3);
45
46 //Accept and incoming connection
47 puts("Waiting for incoming connections...");
48
49 c = sizeof(struct sockaddr_in);
50 new_socket = accept(s , (struct sockaddr *)&client, &c);
51 if (new_socket == INVALID_SOCKET)
52 {
53 printf("accept failed with error code : %d" , WSAGetLastError());
54 }
55
56 puts("Connection accepted");
57 //Reply to client
58 message = "Hello Client , I have received your connection. But I have to go now, bye\n";
59 send(new_socket , message , strlen(message) , 0);
60
61 getchar();
62 closesocket(s);
63 WSACleanup();
64
65 return 0;
66}
67
68
69
70
71
72
73
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you
should see this :
1Hello Client , I have received your connection. But I have to go now, bye
So the client(telnet) received a reply from server. We had to use a getchar because otherwise the output
would scroll out of the client terminal without waiting
We can see that the connection is closed immediately after that simply because the server program
ends after accepting and sending reply. A server like http://www.google.com is always up to accept
incoming connections.
It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we
need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so
that it can receive incoming connections all the time.
Live Server
So a live server will be alive for all time. Lets code this up :
1 /*
2 Live Server on port 8888
3 */
4 #include<io.h>
5 #include<stdio.h>
6 #include<winsock2.h>
7 #pragma comment(lib,"ws2_32.lib") //Winsock Library
8 int main(int argc , char *argv[])
9 {
10 WSADATA wsa;
11 SOCKET s , new_socket;
12 struct sockaddr_in server , client;
13 int c;
14 char *message;
15 printf("\nInitialising Winsock...");
16 if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
17 {
18 printf("Failed. Error Code : %d",WSAGetLastError());
19 return 1;
20 }
21
22 printf("Initialised.\n");
23
24 //Create a socket
25 if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
26 {
27 printf("Could not create socket : %d" , WSAGetLastError());
28 }
29 printf("Socket created.\n");
30
31 //Prepare the sockaddr_in structure
32 server.sin_family = AF_INET;
33 server.sin_addr.s_addr = INADDR_ANY;
34 server.sin_port = htons( 8888 );
35
36 //Bind
37 if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
38 {
39 printf("Bind failed with error code : %d" , WSAGetLastError());
40 exit(EXIT_FAILURE);
41 }
42
43 puts("Bind done");
44 //Listen to incoming connections
45 listen(s , 3);
46
47 //Accept and incoming connection
48 puts("Waiting for incoming connections...");
49
50 c = sizeof(struct sockaddr_in);
51
52 while( (new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET )
53 {
54 puts("Connection accepted");
55
56 //Reply to the client
57 message = "Hello Client , I have received your connection. But I have to go now, bye\n";
58 send(new_socket , message , strlen(message) , 0);
59 }
60
61 if (new_socket == INVALID_SOCKET)
62 {
63 printf("accept failed with error code : %d" , WSAGetLastError());
64 return 1;
65 }
66 closesocket(s);
67 WSACleanup();
68
69 return 0;
70}
71
72
73
74
75
76
We havent done a lot there. Just the accept was put in a loop.
Now run the program in 1 terminal , and open 3 other terminals. From each of the 3 terminal do a telnet to
the server port.
1C:\>telnet
1Welcome to Microsoft Telnet Client
2Escape Character is 'CTRL+]'
3Microsoft Telnet> open localhost 8888
1Hello Client , I have received your connection. But I have to go now, bye
1Initialising Winsock...Initialised.
2Socket created.
3Bind done
4Waiting for incoming connections...
5Connection accepted
6Connection accepted
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 connections.
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
connections.
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.
1
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.
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
Conclusion
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.
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.
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
Advertisement
Advertisements
Report this ad
Report this ad
Share this:
Twitter
Facebook
Related
GCC and Make Compiling, Linking and Building C/C++ ApplicationsIn "C"
This entry was posted in C, CODE::BLOCKS and tagged C Winsock Programming, Winsock, Winsock
Programmin in C Programming. Bookmark the permalink.
← SELECTING BY VERTICAL COLUMN THE PARAGRAPH, PAGE, TEXT OR DATA IN
MICROSOFT WORD
MYSQL: QUERY TOTAL NUMBERS OF SUBSCRIBERS DAILY, WITH COUNT() AND AT THE SAME
QUERY SUM() THE RESULT OF COUNT(), DATE TYPE VARCHAR. →
1. Kerode says:
Pls tell me where did you find ws2_32.lib and where do you put your lib and include files for it to
work
Reply