Академический Документы
Профессиональный Документы
Культура Документы
BinaryTides
CODING
GENERAL
HACKING
LINUX
SOCKET PROGRAMMIN
Create database & reporting apps straight from your database! Try it Buscar
Sockets are the fundamental "things" behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a Escuchar msica socket.
Enter email
RELATED POSTS
ICMP ping flood code using sockets in C Winsock
Initialising Winsock
Winsock first needs to be initialiased like this :
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 / * * /
Receive full data with recv socket functio in C UDP socket programming in winsock Get mac address from ip in winsock
I n i t i a l i s eW i n s o c k
# i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . " ) ; } r e t u r n0 ;
Raw socket programming on windows w Winpcap DNS Query Code in C with winsock Packet Sniffer Code in C using Winsock
Binary Tides
Me gusta A 3555 personas les gusta Binary Tides.
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. OK , so next step is to create a socket.
BinaryTides
Follow
+ 81
Creating a socket
The s o c k e t ( )function is used to create a socket. Here is a code sample :
1 2 3 / * * /
C r e a t eaT C Ps o c k e t
www.binarytides.com/winsock-socket-programming-tutorial/
1/14
22/09/13
3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3
# p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ; } r e t u r n0 ;
Function s o c k e t ( )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 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 :
1 s t r u c ts o c k a d d r _ i ns e r v e r ;
/ /e . g .A F _ I N E T ,A F _ I N E T 6 / /e . g .h t o n s ( 3 4 9 0 ) / /s e es t r u c ti n _ a d d r ,b e l o w / /z e r ot h i si fy o uw a n tt o
t y p e d e fs t r u c ti n _ a d d r{ u n i o n{ s t r u c t{ u _ c h a rs _ b 1 , s _ b 2 , s _ b 3 , s _ b 4 ; }S _ u n _ b ; s t r u c t{ u _ s h o r ts _ w 1 , s _ w 2 ; }S _ u n _ w ; u _ l o n gS _ a d d r ; }S _ u n ; }I N _ A D D R ,* P I N _ A D D R ,F A R* L P I N _ A D D R ; s t r u c ts o c k a d d r{ u n s i g n e ds h o r t c h a r
s a _ f a m i l y ; / /a d d r e s sf a m i l y ,A F _ x x x s a _ d a t a [ 1 4 ] ; / /1 4b y t e so fp r o t o c o la d d r e s s
www.binarytides.com/winsock-socket-programming-tutorial/
2/14
22/09/13
2 5 2 6
} ;
c h a r
s a _ d a t a [ 1 4 ] ; / /1 4b y t e so fp r o t o c o la d d r e s s
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 i n e t _ a d d ris a very handy function to convert an IP address to a long format. This is how you do it :
1 s e r v e r . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 7 4 . 1 2 5 . 2 3 5 . 2 0 " ) ;
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 c o n n e c tfunction. It needs a socket and a sockaddr structure to connect to. Here is a code sample.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 / * * /
C r e a t eaT C Ps o c k e t
# i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts ; s t r u c ts o c k a d d r _ i ns e r v e r ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ;
s e r v e r . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 7 4 . 1 2 5 . 2 3 5 . 2 0 " ) ; s e r v e r . s i n _ f a m i l y=A F _ I N E T ; s e r v e r . s i n _ p o r t=h t o n s (8 0) ; / / C o n n e c tt or e m o t es e r v e r i f( c o n n e c t ( s,( s t r u c ts o c k a d d r* ) & s e r v e r,s i z e o f ( s e r v e r ) )<0 ) { p u t s ( " c o n n e c te r r o r " ) ; r e t u r n1 ; } p u t s ( " C o n n e c t e d " ) ; } r e t u r n0 ;
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 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 pipe which is not interfered by other data. 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 s e n dwill 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 3 4 5 6 7 / * * /
C r e a t eaT C Ps o c k e t
www.binarytides.com/winsock-socket-programming-tutorial/
3/14
22/09/13
7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8
p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ; s e r v e r . s i n _ a d d r . s _ a d d r=i n e t _ a d d r ( " 7 4 . 1 2 5 . 2 3 5 . 2 0 " ) ; s e r v e r . s i n _ f a m i l y=A F _ I N E T ; s e r v e r . s i n _ p o r t=h t o n s (8 0) ; / / C o n n e c tt or e m o t es e r v e r i f( c o n n e c t ( s,( s t r u c ts o c k a d d r* ) & s e r v e r,s i z e o f ( s e r v e r ) )<0 ) { p u t s ( " c o n n e c te r r o r " ) ; r e t u r n1 ; } p u t s ( " C o n n e c t e d " ) ; / / S e n ds o m ed a t a m e s s a g e=" G E T/H T T P / 1 . 1 \ r \ n \ r \ n " ; i f (s e n d ( s,m e s s a g e,s t r l e n ( m e s s a g e ),0 )<0 ) { p u t s ( " S e n df a i l e d " ) ; r e t u r n1 ; } p u t s ( " D a t aS e n d \ n " ) ; } r e t u r n0 ;
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 r e c vis 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.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 / * * /
C r e a t eaT C Ps o c k e t
# i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts ; s t r u c ts o c k a d d r _ i ns e r v e r ; c h a r* m e s s a g e,s e r v e r _ r e p l y [ 2 0 0 0 ] ; i n tr e c v _ s i z e ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ;
www.binarytides.com/winsock-socket-programming-tutorial/
4/14
22/09/13
3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1
We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com 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 c l o s e s o c k e tis used to close the socket. Also WSACleanup must be called to unload the winsock library (ws2_32.dll).
1 2 c l o s e s o c k e t ( s ) ; W S A C l e a n u p ( ) ;
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 www.google.com
www.binarytides.com/winsock-socket-programming-tutorial/
5/14
22/09/13
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 www.google.com is a server and your web browser is a client. Or more technically 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.
The h _ a d d r _ l i s thas the IP addresses. So now lets have some code to use them.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 / * * /
G e tI Pa d d r e s sf r o md o m a i nn a m e
# i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; c h a r* h o s t n a m e=" w w w . g o o g l e . c o m " ; c h a ri p [ 1 0 0 ] ; s t r u c th o s t e n t* h e ; s t r u c ti n _ a d d r* * a d d r _ l i s t ; i n ti ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; i f (( h e=g e t h o s t b y n a m e (h o s t n a m e))= =N U L L ) { / / g e t h o s t b y n a m ef a i l e d p r i n t f ( " g e t h o s t b y n a m ef a i l e d:% d ",W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } / / C a s tt h eh _ a d d r _ l i s tt oi n _ a d d r,s i n c eh _ a d d r _ l i s ta l s oh a st h ei pa d d r e s si nl o n gf o r m a to n l y a d d r _ l i s t=( s t r u c ti n _ a d d r* * )h e > h _ a d d r _ l i s t ; f o r ( i=0 ;a d d r _ l i s t [ i ]! =N U L L ;i + + ) { / / R e t u r nt h ef i r s to n e ; s t r c p y ( i p,i n e t _ n t o a ( * a d d r _ l i s t [ i ] )) ; } p r i n t f ( " % sr e s o l v e dt o:% s \ n ",h o s t n a m e,i p ) ; r e t u r n0 ; r e t u r n0 ;
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 i n e t _ n t o awill convert an IP address in long format to dotted format. This is just the opposite of i n e t _ a d d r . So far we have see some important structures that are used. Lets revise them : 1. s o c k a d d r _ i n- Connection information. Used by connect , send , recv etc.
www.binarytides.com/winsock-socket-programming-tutorial/
6/14
22/09/13
2. i n _ a d d r- Ip address in long format 3. s o c k a d d r
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 We have already learnt how to open a socket. So the next thing would be to bind it.
Bind a socket
Function b i n dcan be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function. Lets see a code example :
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 / * * /
B i n ds o c k e tt op o r t8 8 8 8o nl o c a l h o s t
# i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts ; s t r u c ts o c k a d d r _ i ns e r v e r ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ; / / P r e p a r et h es o c k a d d r _ i ns t r u c t u r e s e r v e r . s i n _ f a m i l y=A F _ I N E T ; s e r v e r . s i n _ a d d r . s _ a d d r=I N A D D R _ A N Y ; s e r v e r . s i n _ p o r t=h t o n s (8 8 8 8) ; / / B i n d i f (b i n d ( s, ( s t r u c ts o c k a d d r* ) & s e r v e r,s i z e o f ( s e r v e r ) )= =S O C K E T _ E R R O R ) { p r i n t f ( " B i n df a i l e dw i t he r r o rc o d e:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p u t s ( " B i n dd o n e " ) ; c l o s e s o c k e t ( s ) ; } r e t u r n0 ;
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.
www.binarytides.com/winsock-socket-programming-tutorial/
7/14
22/09/13
Thats all. Now comes the main part of accepting new connections.
Accept connection
Function a c c e p tis used for this. Here is the code
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 / * * /
B i n ds o c k e tt op o r t8 8 8 8o nl o c a l h o s t
# i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts,n e w _ s o c k e t ; s t r u c ts o c k a d d r _ i ns e r v e r,c l i e n t ; i n tc ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ; / / P r e p a r et h es o c k a d d r _ i ns t r u c t u r e s e r v e r . s i n _ f a m i l y=A F _ I N E T ; s e r v e r . s i n _ a d d r . s _ a d d r=I N A D D R _ A N Y ; s e r v e r . s i n _ p o r t=h t o n s (8 8 8 8) ; / / B i n d i f (b i n d ( s, ( s t r u c ts o c k a d d r* ) & s e r v e r,s i z e o f ( s e r v e r ) )= =S O C K E T _ E R R O R ) { p r i n t f ( " B i n df a i l e dw i t he r r o rc o d e:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p u t s ( " B i n dd o n e " ) ; / / L i s t e nt oi n c o m i n gc o n n e c t i o n s l i s t e n ( s,3 ) ; / / A c c e p ta n di n c o m i n gc o n n e c t i o n p u t s ( " W a i t i n gf o ri n c o m i n gc o n n e c t i o n s . . . " ) ; c=s i z e o f ( s t r u c ts o c k a d d r _ i n ) ; n e w _ s o c k e t=a c c e p t ( s,( s t r u c ts o c k a d d r* ) & c l i e n t ,& c ) ; i f( n e w _ s o c k e t= =I N V A L I D _ S O C K E T ) { p r i n t f ( " a c c e p tf a i l e dw i t he r r o rc o d e:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p u t s ( " C o n n e c t i o na c c e p t e d " ) ; c l o s e s o c k e t ( s ) ; W S A C l e a n u p ( ) ; } r e t u r n0 ;
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
1 t e l n e tl o c a l h o s t8 8 8 8
www.binarytides.com/winsock-socket-programming-tutorial/
8/14
22/09/13
4 5 6 W a i t i n gf o ri n c o m i n gc o n n e c t i o n s . . . C o n n e c t i o na c c e p t e d P r e s sa n yk e yt oc o n t i n u e
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 :
1 2 c h a r* c l i e n t _ i p=i n e t _ n t o a ( c l i e n t . s i n _ a d d r ) ; i n tc l i e n t _ p o r t=n t o h s ( c l i e n t . s i n _ p o r t ) ;
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 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 / *
B i n ds o c k e tt op o r t8 8 8 8o nl o c a l h o s t * / # i n c l u d e < i o . h > # i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts,n e w _ s o c k e t ; s t r u c ts o c k a d d r _ i ns e r v e r,c l i e n t ; i n tc ; c h a r* m e s s a g e ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ; / / P r e p a r et h es o c k a d d r _ i ns t r u c t u r e s e r v e r . s i n _ f a m i l y=A F _ I N E T ; s e r v e r . s i n _ a d d r . s _ a d d r=I N A D D R _ A N Y ; s e r v e r . s i n _ p o r t=h t o n s (8 8 8 8) ; / / B i n d i f (b i n d ( s, ( s t r u c ts o c k a d d r* ) & s e r v e r,s i z e o f ( s e r v e r ) )= =S O C K E T _ E R R O R ) { p r i n t f ( " B i n df a i l e dw i t he r r o rc o d e:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p u t s ( " B i n dd o n e " ) ; / / L i s t e nt oi n c o m i n gc o n n e c t i o n s l i s t e n ( s,3 ) ; / / A c c e p ta n di n c o m i n gc o n n e c t i o n p u t s ( " W a i t i n gf o ri n c o m i n gc o n n e c t i o n s . . . " ) ; c=s i z e o f ( s t r u c ts o c k a d d r _ i n ) ; n e w _ s o c k e t=a c c e p t ( s,( s t r u c ts o c k a d d r* ) & c l i e n t ,& c ) ; i f( n e w _ s o c k e t= =I N V A L I D _ S O C K E T ) { p r i n t f ( " a c c e p tf a i l e dw i t he r r o rc o d e:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p u t s ( " C o n n e c t i o na c c e p t e d " ) ; / / R e p l yt oc l i e n t m e s s a g e=" H e l l oC l i e n t,Ih a v er e c e i v e dy o u rc o n n e c t i o n .B u tIh a v et og on o w ,b y e \ n " ; s e n d ( n e w _ s o c k e t,m e s s a g e,s t r l e n ( m e s s a g e ),0 ) ; g e t c h a r ( ) ; c l o s e s o c k e t ( s ) ; W S A C l e a n u p ( ) ; } r e t u r n0 ;
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
www.binarytides.com/winsock-socket-programming-tutorial/
9/14
22/09/13
1
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 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 a c c e p tin 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 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4 7 5 7 6 / *
L i v eS e r v e ro np o r t8 8 8 8 * / # i n c l u d e < i o . h > # i n c l u d e < s t d i o . h > # i n c l u d e < w i n s o c k 2 . h > # p r a g m ac o m m e n t ( l i b , " w s 2 _ 3 2 . l i b " )/ / W i n s o c kL i b r a r y i n tm a i n ( i n ta r g c,c h a r* a r g v [ ] ) { W S A D A T Aw s a ; S O C K E Ts,n e w _ s o c k e t ; s t r u c ts o c k a d d r _ i ns e r v e r,c l i e n t ; i n tc ; c h a r* m e s s a g e ; p r i n t f ( " \ n I n i t i a l i s i n gW i n s o c k . . . " ) ; i f( W S A S t a r t u p ( M A K E W O R D ( 2 , 2 ) , & w s a )! =0 ) { p r i n t f ( " F a i l e d .E r r o rC o d e:% d " , W S A G e t L a s t E r r o r ( ) ) ; r e t u r n1 ; } p r i n t f ( " I n i t i a l i s e d . \ n " ) ; / / C r e a t eas o c k e t i f ( ( s=s o c k e t ( A F _ I N E T,S O C K _ S T R E A M,0) )= =I N V A L I D _ S O C K E T ) { p r i n t f ( " C o u l dn o tc r e a t es o c k e t:% d ",W S A G e t L a s t E r r o r ( ) ) ; } p r i n t f ( " S o c k e tc r e a t e d . \ n " ) ; / / P r e p a r et h es o c k a d d r _ i ns t r u c t u r e s e r v e r . s i n _ f a m i l y=A F _ I N E T ; s e r v e r . s i n _ a d d r . s _ a d d r=I N A D D R _ A N Y ; s e r v e r . s i n _ p o r t=h t o n s (8 8 8 8) ; / / B i n d i f (b i n d ( s, ( s t r u c ts o c k a d d r* ) & s e r v e r,s i z e o f ( s e r v e r ) )= =S O C K E T _ E R R O R ) { p r i n t f ( " B i n df a i l e dw i t he r r o rc o d e:% d ",W S A G e t L a s t E r r o r ( ) ) ; e x i t ( E X I T _ F A I L U R E ) ; } p u t s ( " B i n dd o n e " ) ; / / L i s t e nt oi n c o m i n gc o n n e c t i o n s l i s t e n ( s,3 ) ; / / A c c e p ta n di n c o m i n gc o n n e c t i o n p u t s ( " W a i t i n gf o ri n c o m i n gc o n n e c t i o n s . . . " ) ; c=s i z e o f ( s t r u c ts o c k a d d r _ i n ) ; w h i l e (( n e w _ s o c k e t=a c c e p t ( s,( s t r u c ts o c k a d d r* ) & c l i e n t ,& c ) )! =I N V A L I D _ S O C K E T) { p u t s ( " C o n n e c t i o na c c e p t e d " ) ; / / R e p l yt ot h ec l i e n t m e s s a g e=" H e l l oC l i e n t,Ih a v er e c e i v e dy o u rc o n n e c t i o n .B u tIh a v et og on o w ,b y e \ n " s e n d ( n e w _ s o c k e t,m e s s a g e,s t r l e n ( m e s s a g e ),0 ) ;
www.binarytides.com/winsock-socket-programming-tutorial/
10/14
22/09/13
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. Run telnet like this
1 1 2 3 1 C : \ > t e l n e t W e l c o m et oM i c r o s o f tT e l n e tC l i e n t E s c a p eC h a r a c t e ri s' C T R L + ] ' M i c r o s o f tT e l n e t >o p e nl o c a l h o s t8 8 8 8 H e l l oC l i e n t,Ih a v er e c e i v e dy o u rc o n n e c t i o n .B u tIh a v et og on o w ,b y e
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.
1
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 :
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. So the connection handler can be rewritten like this :
1
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
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. 3. Winsock function to close a socket is c l o s e s o c k e t, whereas on Linux it is c l o s e . On Winsock WSACleanup must also be called to unload the winsock dll.
www.binarytides.com/winsock-socket-programming-tutorial/
11/14
22/09/13
is filled with the error number. And there are many more differences as we go deep.
4. On winsock the error number is fetched by the function W S A G e t L a s t E r r o r ( ) . On Linux the errno variable from errno.h file
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.
Last Updated On : 12th December 2012 socket programming winsock winsock tutorial
Related Posts
UDP socket programming in winsock Raw socket programming on windows with winsock Socket programming in C on Linux tutorial Code a simple tcp socket server in winsock Perl socket programming tutorial About Silver Moon
Php developer, blogger and Linux enthusiast. He can be reached at m00n.silv3r@gmail.com. Or find him on Google+
Share
i 'm trying to compile and test run your code i keep getting this errors undefined reference to _imp_WSAStartup@8 and undefined reference to _imp_WSACloseup@0. i think it is as a result of compilation error.please i need in detail how to compile winsock codes in c.
2
Reply
Share
Avatar
B arn
8 months ago
Are you sure that you can call WSAGetLastError if WSAStartup fails? From what I remember it loads the winsock dll, so if it isnt loaded, WSAGetLastError wouldn't be available.
2 Reply Share
Mod
S ilver Moon
> Barn
6 months ago
It would be available even if WSAStartup fails. the documentation says : "TheWSAGetLastError function is one of the only functions in the Winsock 2.2 DLL that can be called in the case of aWSAStartup failure."
Avatar
Neel
http://msdn.microsoft.com/en-u...
Reply Share
11 months ago
You have given great knowledge buddy. I was searching for page like this for more than 2 weeks, I extend you my heartiest appreciation.
1
Reply
Share
Avatar
Luis 1
a year ago
Avatar
A s t rid
6 days ago
Avatar
s us hil
19 days ago
www.binarytides.com/winsock-socket-programming-tutorial/
12/14
22/09/13 Avatar
Avatar
Jac op
a month ago
Avatar
handling connections part is broken i think.(if u can repair it can be good :) this topic was a good tutorial for understanding how to use sockets )
Reply Share
3 months ago
S uperInvit ado
Avatar
fahad
4 months ago
Greetings on typing this line from heading "Recieving data" line 41 it gives error under "(struct sockaddr *)&server" intelliSense: argument of type "sockaddr *" is incompatible with parameter of type "const sockaddr *"
Avatar
fahad
4 months ago
what if i have to send data from linux box to windows box can i use the client side code of linux socket programming and server side of windows socket programing?????or there are some special changes that are needed to be done??? sorry if u find my question lame. i m complete beginer
Reply Share
Mod
S ilver Moon
> fahad
4 months ago
yes, you are correct. It would work like that. the code should work without any changes, just that the client needs to connect on the correct port which the server has opened.
Reply fahad Share
4 months ago
Avatar
t arun
7 months ago
but all this tutorial does not tell about how can we send some text to server..when we run your code it simply say connection created and output is "Hello Client , I have received your connection. But I have to go now, bye. but what if we want to chat with server or want to send some message?
Reply Share
Mod
S ilver Moon
> tarun
Share
6 months ago
Avatar
Mark
9 months ago
S ilver Moon
> Mark
6 months ago
Avatar
Thomas Gray
http://www.binarytides.com/cod...
Reply Share
10 months ago
Great tutorial ! Well explained , clear and concise. I would greatly appreciate it if you could upload the code snippets related to handling connections using threads.
Thanks !
Reply Share
www.binarytides.com/winsock-socket-programming-tutorial/
13/14
22/09/13
S ilver Moon
Mod
6 months ago
Avatar
Y oges h
connections can be handled with the select function. check this post http://www.binarytides.com/cod...
Reply
10 months ago
S ilver Moon
> Yogesh
10 months ago
Avatar
Y oges h
I would suggest learning the winsock basics from google/internet. there are plenty of sites and tutorials out there. then try building a real socket application and the process of development shall teach you more.
Reply Share
10 months ago
Hello, This is a great tutorial for beginners like me. You have kept it SSS - short, sweet, simple :). But I am facing one problem - I am not able to connect to a remote server. I have used your program as it is, except server ip address. Socket is getting created but 'connect error' is coming. Do I need to change the port number? I tried with different port numbers but in vain. I have run this program from my company. Is company's firewall creating problem? Please guide me to run this program I
Reply Share
Mod
S ilver Moon
> Yogesh
10 months ago
you can connect to a remote ip+port only if the port is open. So first check if the port is really open or not This can be done by running the following command in the terminal telnet 1.2.3.4 900 where 1.2.3.4 is the remote ip address and 900 is the port. If telnet shows the port as open, then the socket program shown in this post should also connect easily. If telnet fails, then the socket program will also fail since they both are doing the same thing.
Reply Y oges h Share
10 months ago
Hello, Thanks for quick reply. I followed your instructions, the google port is not open. But I want to see the successful connection by any means :). Can I connect to own computer? Or there is another way to achieve this?
Reply Share
Mod
S ilver Moon
> Yogesh
10 months ago
Avatar
Mark W hit ney
a year ago
you can do a ping www.google.com in your terminal, it will give you the ip address of google.com then try connecting to port 80 of that ip. it should work.
Reply Share
Great tutorial, but where are the code examples for the threads? I just see empty boxes in the Handling Connections section.
Reply Share
Mod
S ilver Moon
6 months ago
About
Su b s cri b e
Ad d D i s q u s to yo u r s i te
www.binarytides.com/winsock-socket-programming-tutorial/
14/14