Documents

19 pages
356 views

Winsock Tutorial – Socket Programming in C on Windows

of 19
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Share
Description
socket programming
Transcript
  9/5/2017Winsock tutorial – Socket programming in C on windowshttp://www.binarytides.com/winsock-socket-programming-tutorial/1/19 Winsock By Silver Moon On Dec 26, 2011 51 Comments Winsock tutorial – Socket programming in C on windows BinaryTides Genuine how-to guides on Linux, Ubuntu and FOSSHOMEAPPSCODING ▼ DISTROS ▼ GENERAL ▼ LINUX ▼ REVIEWSSECURITY ▼ SERVER ▼ SUPER TIPS Socket programming with winsock This is a quick guide/tutorial to learning socket programming in C language on Windows. Windows because thecode snippets shown over here will work only on Windows. The windows api to socket programming is calledwinsock.Sockets are the fundamental things behind any kind of network communications done by your computer. For examplewhen you type www.google.com in your web browser, it opensa socket and connects to google.com to fetch the page andshow 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 ExpressEdition. 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 theprogram 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 theversion we want to load and second one is a WSADATA structure which will hold additional information afterwinsock has been loaded. 123456789101112131415161718192021222324/* Initialise Winsock*/ #include<stdio.h>#include<winsock2.h> #pragma comment(lib, ws2_32.lib ) //Winsock Library  int  main( int  argc , h r  *argv[]){ WSADATA wsa;  printf ( \nInitialising Winsock... );  if  (WSAStartup(MAKEWORD(2,2),&wsa) != 0) {  printf ( Failed. Error Code : %d ,WSAGetLastError());  return  1; }  printf ( Initialised. );  return  0;} Custom Search SEARCH Connect with us     Other interesting stuff  Packet Sniffer Code in C usingWinsockUDP socket programming in winsockGet mac address from ip in winsockTCP Connect Port Scanner SourceCode in C with Winsock  9/5/2017Winsock tutorial – Socket programming in C on windowshttp://www.binarytides.com/winsock-socket-programming-tutorial/2/19 If any error occurs then the WSAStartup function would return a non zero value and WSAGetLastError can be usedto get more information about what error happened.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 networkcommands. 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 hereOk , so you have created a socket successfully. But what next ? Next we shall try to connect to some server usingthis socket. We can connect to www.google.com Note Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDPprotocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCPsockets. 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 toconnect to.To connect to a remote server we need to do a couple of things. First is create a sockaddr_in structure with propervalues filled in. Lets create one for ourselves : 123456789101112131415161718192021222324252627282930313233/* Create a TCP socket*/ #include<stdio.h>#include<winsock2.h> #pragma comment(lib, ws2_32.lib ) //Winsock Library  int  main( int  argc , h r  *argv[]){ WSADATA wsa; SOCKET s;  printf ( \nInitialising Winsock... );  if  (WSAStartup(MAKEWORD(2,2),&wsa) != 0) {  printf ( Failed. Error Code : %d ,WSAGetLastError());  return  1; }  printf ( Initialised.\n );  if ((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET) {  printf ( Could not create socket : %d  , WSAGetLastError());  }  printf ( Socket created.\n );  return  0;}1  stru t  sockaddr_in server; Raw socket programminon windows with winsockDNS Query Code in C with winsock  9/5/2017Winsock tutorial – Socket programming in C on windowshttp://www.binarytides.com/winsock-socket-programming-tutorial/3/19 Have a look at the structuresThe sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. Itcontains 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 :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 acode sample. stru t  1234567891011121314151617181920212223242526// IPv4 AF_INET sockets: stru t  sockaddr_in {  short  sin_family; // e.g. AF_INET, AF_INET6 unsigned short  sin_port; // e.g. htons(3490)  stru t  in_addr sin_addr; // see struct in_addr, below  h r  sin_zero[8]; // zero this if you want to};  typedef   stru t  in_addr {  union  {  stru t  { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;  stru t  { u_short s_w1,s_w2; } S_un_w; u_long S_addr; } S_un;} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;  stru t  sockaddr { unsigned short  sa_family; // address family, AF_xxx  h r  sa_data[14]; // 14 bytes of protocol address};1server.sin_addr.s_addr = inet_addr( 74.125.235.20 ); 12345678910111213141516171819202122232425262728293031323334353637383940414243444546/* Create a TCP socket*/ #include<stdio.h>#include<winsock2.h> #pragma comment(lib, ws2_32.lib ) //Winsock Library  int  main( int  argc , h r  *argv[]){ WSADATA wsa; SOCKET s;  stru t  sockaddr_in server;  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 , ( stru t  sockaddr *)&server , sizeof (server)) < 0) {  puts ( connect error );  return  1; }  puts ( Connected );  return    9/5/2017Winsock tutorial – Socket programming in C on windowshttp://www.binarytides.com/winsock-socket-programming-tutorial/4/19 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 portis not open for connection.OK , so we are now connected. Lets do the next thing , sending some data to the remote server. Quick Note The concept of connections apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable stream of data such that there can be multiple such streams each having communication of its own. Think of this as a pipewhich is not interfered by other data.Other sockets like UDP , ICMP , ARP dont have a concept of connection . These are non-connection basedcommunication. 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 :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. 4748  return  0;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/* Create a TCP socket*/ #include<stdio.h>#include<winsock2.h> #pragma comment(lib, ws2_32.lib ) //Winsock Library  int  main( int  argc , h r  *argv[]){ WSADATA wsa; SOCKET s;  stru t  sockaddr_in server;  h r  *message;  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 , ( stru t  sockaddr *)&server , sizeof (server)) < 0) {  puts ( connect error );  return  1; }  puts ( Connected ); //Send some data message = GET / HTTP/1.1\r\n\r\n ;   if ( send(s , message , strlen (message) , 0) < 0) {  puts ( Send failed );  return  1; }  puts ( Data Send\n );  return  0;}
Related Documents
View more...
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks