The site moved to root domain where all post are imported. Please go to http://pusheax.com/
To write any windows program we are required to include the “windows.h” . And for the socket we need only “winsock2.h”. Only two required header we need are:
Well, Let’s go step by step with example:
In line 7 WSAData is a structure name which holds the information about windows socket implementation. So here we declare our own new object to work with called “version”. About WSAData here you will get more in details.
In line 8 MAKEWORD() is a macro which is type of WORD. MAKEWORD(2,2) is going to be “2.2”.
Compile the code and run , if you are in xp+ then you will get output “Good – Everything fine”
Since everything fine , So we want to create our real socket using structure name “SOCKET“:
Our second step is creating socket. So in line 17 we declare the variable of SOCKET called u_sock and store the socket() function.
AF_INET specify to use ipv4.
SOCK_STREAM to specify that two connection based and reliable which used by AF_INET.
IPPROTO_TCP specify that its Internet Protocol (TCP/IP).
You can get more details in this link http://msdn.microsoft.com/en-us/library/windows/desktop/ms740506%28v=vs.85%29.aspx .
If something wrong creating the socket then it return the value “INVALID_SOCKET” which we checked in line 18.
Time to specify address and make connection. For bit theory and basic idea read: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740496%28v=vs.85%29.aspx and connect() function http://msdn.microsoft.com/en-us/library/windows/desktop/ms737625%28v=vs.85%29.aspx.
The code for address information and using connect() function:
In the above example line 25 we declare the object to work with. Then in 26 we specify to go with ipv4 , in line 27 we set our target address to connect to and in line 28 we set port number.
Line number 33 to 36 checking if there is anything wrong, connect() function return error code SOCKET_ERROR when unsuccessful. If so we check the Error code number then close the socket using closesocket() function.
In line 42 we define a string to send to remote address. Line 43 declaring an array to hold output of the command.
Line number 45 , we store the send() and the required parameters . u_sock is the name of the created socket , mymsg has the command to send to the remote address, Maximum length of the command, And the flag.
In the line 51 , we used recv() to get output and store to an array. The parameters of this function same as send().
Line number 55, Getting the output from the array and printing in the screen then line 56 closing the socket.
I hope i made this article simpler to understand. I don’t really like to write too much theory since there are lots and not that useful to me(may be to you too). If you have any questions , please comment!
Hope you enjoyed!