windows socket programming in c - biniam fisseha

Upload: biniam-f

Post on 11-Feb-2018

235 views

Category:

Documents


4 download

TRANSCRIPT

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    1/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    I n t r o d u c t io n t o So c k e t P ro g ra m m in g

    Alm ost a l l W in sock f unct ions oper ate on a sock et, as i t is our hand le to t he connect ion . Both

    sides of th e connect i on u se a socket, and t hey are n ot p latfo r m -speci f ic ( i .e. a W in dow s andUN IX m achin e can ta lk to each ot her using sockets). Sockets ar e also tw o-w ay; data can b ebo th sent and r eceived on a socket.

    Th ere ar e t w o com m on ty pes for socket, one i s a str eam in g socket (SOCK_STREAM) , theo t h e r i s a d a t agr a m so ck e t ( SOCK _D GRA M ) . T h e s tr e am i n g v a r i an t i s d esi gn e d f o rapp l i ca t ions that need a re l iab le connect ion , o f ten us ing cont inuous s t reams o f da ta . Thepr otocol used for t h is typ e of socket is TCP.

    D a t agr a m so ck e t s u se U DP as u n d er l y i n g p r o t o c ol , a r e c o n nec t io n l ess , a nd h av e am ax imu m buf fer s ize . They ar e in tended for app l i cat ions th at send data in smal l packages

    and th at do no t r equ i r e per fec t re l iab i l i ty . Un l i ke st r eam ing sockets , da tagram sockets donot guarantee data w i l l r each i ts dest ina t ion or tha t i t comes in t he r igh t o r der . Datagramsock ets can be s l igh t l y faster and usefu l fo r app l i cat ions l i k e s t ream ing aud io or v ideo,w h er e r e li ab i l i t y i s n o t a s h i gh o n t h e p r i o r i t y l i st a s sp e ed an d l at e ncy . W h e r e t h er e l iab i l i ty i s requ i r ed, st r eam ing sockets are used.

    W insock i s a s tandard app l i cat ion pr ogram m ing in ter face ( API) tha t a l low s t w o or m or ea p p l i ca t i o n s ( o r p r o c esse s) t o c o m m u n i c at e e i t h er o n t h e s am e m ac h i n e o r a cr o ss anetw or k and i s p r im ar i l y designed to fos ter d ata com m unicat ion over a netw or k . I t shou ldbe n oted that W insock i s a netw or k pr ogram m ing in ter face and not a pr o toco l . W insockp r o v i d es t h e p r o g r a m m i n g i n t er f ac e f o r ap p l i ca t io n s t o c om m u n i c at e u si n g p o p u l ar

    netw or k pr o toco ls such as Tr ansm ission Cont ro l Pro toco l / In tern et Pro toco l ( TCP/ IP) andIn t ernetw ork Packet Exchange ( IPX) . The W insock in ter face inher i ts a great dea l f ro m theBSD Sockets im p lem enta t ion on UNIX p la t fo rm s . In W indow s env i r onm ents , the in ter faceh a s e v o l v ed i n t o a t r u l y p r o t o co l - in d e p e n d e n t i n t e r f a ce , es p ec ia l ly w i t h t h e r e l ea se o fW in sock 2.

    W in sock is avai lable in tw o m ajor ver sions W in sock 1 an d W insock 2 on al l W in do w sp la t fo r m s except W indow s CE ( W indo w s CE, e .g . W ind ow s m obi le , has on ly W insock 1) .W h e n d ev e lo p i n g n ew a p p li ca t io n s w e sh o u l d t a r ge t t h e W i n s oc k 2 sp ec i fi ca t io n b yi n c lu d i n g W I N SOCK 2 .H i n o u r a p p li cat i o n . Fo r c om p a t ib i l i t y w i t h o l de r W i n so ckapp l i ca t ions and w hen deve lop ing on W indow s CE p la t fo r m s , W INSOCK.H is avai lab le .

    Th ere i s a lso an add i t iona l header f i l e : MSW SOCK.H, w h ich ta r gets M icr osoft -spec i f i cpr ogram m ing extension s that ar e nor m al ly used for develop ing h igh per form ance W insockapp l i ca t ions.

    Th e W insock 2 Serv ice Pro v ider In t er face (SPI) i s the com p lement to the W insock . As thenam e im pl i es, th e SPI is a ser vice to app l icat io ns and is no t an app l icat ion . I t is w r i t t en andexposes i tse lf t o app l i ca t ions t hat can load th e serv ice e i ther k now ing ly or un know ing ly .T h e SP I i s a p a r t o f t h e W i n s ock 2 sp e ci f i ca t i o n a n d t h e r e fo r e r e q u i r e s t h e W i n s ock 2up date i f r un n ing in W indo w s 95. The fo l low ing f igur e i l l us t ra tes the re la t ionsh ip b etw eenW in sock appl icat ion s and th e SPI.

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    2/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    Th ere ar e tw o par ts to the SPI: t ran spo r t ser vice pr ovid ers and nam e space pr ovid ers. Eachp a r t p r o v i d e s d i st i n c t l y d i f f e r en t f u n c t i o n al i t i es . T h e r e a r e t w o t y p e s o f t r a n sp o r t se r v i c ep r o v i d e r s: l a y e r e d a n d b a se . A l a y e r e d s e r v i ce p r o v i d er i n s t al l s i t s el f i n t o t h e W i n so ck

    cata log above base prov iders and poss ib ly betw een o ther layered p r ov ider s and in terceptsW insock API ca l l s f r om app l i cat ions. A b ase pr ov ider exposes a W insock in ter face thatdi r ect ly i m plem ents a pr ot ocol such as the M icrosoft TCP/ IP pr ovid er .

    SPI Archite cture

    W hen com p i l ing our app l i cat ion w i th W INSOCK2.H, w e shou ld l ink w i th W S2_32.L IBl ib r ary . W hen using W IN SOCK.H (as o n W ind ow s CE) w e shou ld use W SOCK32 .LIB. I f w euse extension APIs f r om M SW SOCK.H, w e m ust a lso l ink w i th M SW SOCK.DLL. Once w eh a v e i n c l u d e d t h e n e c essa r y h ea d er f i l es a n d l i n k e n v i r o n m e n t , w e a r e r e ad y t o b e gi ncod ing our app l i cat ion , w h ich requ i res in i t ia l i z ing Wi nsock .

    W in d o w s So c k e t P r o g ra m m in g in C

    No w t h a t t h e e n v i r o n m e n t i s r ea d y , le t s s ee t h e n e c ess ar y s t ep s i n c r e at i n g a w o r k i n gnetw or k app l i cat ion . Every W insock app l i cat ion m ust load the appr opr ia te vers ion o f t heW insock DLL. I f w e fa i l to load the W insock l ib r ary before ca ll ing a W insock funct ion , th e

    f u n c t i o n r e t u r n s a SOCKET_ERROR; t h e e r r o r t h a t w e g et a f t er t h e c al l t o WSAGetLastErrorw i l l be WSANOTINITIALISED. Load ing t he W insock l ib r ary i s accom p l i shed by cal l ing t heWSAStartup fun ct ion , w hich is def in ed as

    int WSAStartup(

    WORD wVersionRequested,

    LPWSADATA lpWSAData

    );

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    3/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    T h e wVersionRequested par amet er is used to speci fy t he version o f the W insock l ib r ary w ew ant to load. The h igh-order by t e spec i f ies the m inor vers ion o f t he r equested W insockl i b r a r y , w h i l e t h e l o w - or d e r b y t e i s t h e m a jo r v er s i on . W e ca n u se t h e h a n d y m a c r o

    MAKEWORD(x, y), i n w h ich x i s t h e h i g h b y t e a n d y i s t h e l o w b y t e , t o o b t a i n t h e c o r r ec tv a l u e f o r wVersionRequested. T h e f o l lo w i n g e xa m p l e d e m o n st r a t es h o w w e i n i t i a l i ze aspec i f i c vers ion o f the Wi nsock l ib rar y .

    WSADATA wsadata;

    if (WSAStartup(MAKEWORD(2, 0), &wsadata) != 0)

    {

    printf("WSA Initialization failed.");

    }

    Note that a f te r a successfu l ca l l to WSAStartup, t h e wsadata var iab le w i l l be f i l l ed w i th

    in format ion about the loaded l ib rary .

    W hen our app l i ca t ion i s comp le te ly f in ished us ing the W insock in ter face, w e shou ld cal lWSACleanup, w h ich a l low s W insock to f ree u p any resources a llocated by W insock andcancel any pen din g W in sock cal ls th at our appl icat ion m ade. WSACleanup is def ined as

    int WSACleanup(void);

    Fai lu r e to ca l l WSACleanup w hen our app l i cat ion ex i ts i s no t h arm fu l because the opera t in gsystem w i l l f r ee up r esour ces aut om at ical ly . How ever, our app l icat ion w i l l not be fo l low ing

    th e W insock speci f icat ion . Also, w e should cal l WSACleanup fo r each cal l t ha t i s m ade to

    WSAStartup.

    I P v 4 Is su e s

    In IPv 4, com pu ter s are assigned an addr ess th at is r epr esented as a 32-bi t qu ant i ty . W hen acl ient w ant s to com m un icate w i th a server th r ough TCP or UDP, i t m ust speci fy the serv er ' sI P a d d r ess a lo n g w i t h a ser v i c e p o r t n u m b e r . A l s o, w h e n s er v e r s w a n t t o l i st en f o rincom ing c l ien t r equests , they m ust spec i fy an IP addr ess and a por t num ber . In W insock ,a p p l i ca t i o n s sp e ci f y I P a d d r e sse s an d se r v i ce p o r t i n f o r m a t i o n t h r o u g h t h e SOCKADDR_INstr uctur e, w hich is def ined as

    struct sockaddr_in{

    short sin_family;

    u_short sin_port;

    struct in_addr sin_addr;

    char sin_zero[8];

    };

    T h e sin_family f i e ld m ust be se t to AF_INET, w h i c h t e l ls W i n s o ck w e ar e u si n g t h e I Paddr ess fami ly .

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    4/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    T h e sin_port f ie ld d ef ines w hich TCP or UDP com m un icat ion p or t w i l l be used to ident i fy aserver ser vice. App l icat ion s should be par t i cular ly car eful in choo sing a por t because som eof th e ava i lab le p or t num bers are r eserved for w e l l -kn ow n serv ices, such as F i le Tr ansfer

    Pro t oco l ( FTP) and Hyper tex t Transfer Pro t oco l (H TTP).

    T h e sin_addr f i el d o f t h e SOCKADDR_IN st ruc ture i s used for s tor ing an IPv4 address as af o u r - b y t e q u a n t i t y , w h i ch i s an u n s ig n ed l o n g i n t e ge r d a t a t y p e . De p en d i n g o n h o w t h i sf ie ld i s used, i t can repr esent a local o r a r em ote I P address. IP addr esses are nor m al lyspec i f ied in I n t er net s tandard dot t ed not a t ion as a .b .c .d . Each le t t e r r epresents a num ber( in decim al , octal , or h exadecim al form at) for each by te and is assigned, fr om left t o r igh t, tot h e f o u r b y t e s o f t h e u n s i g n e d l o n g i n t e g e r . T h e f i n a l f i e l d , sin_zero, f u n c t i o n s o n l y a s

    pad din g to m ake the SOCKADDR_IN stru ctu re t he sam e size as th e SOCKADDR s t r u c t u r e .

    A u s ef u l s u p p o r t f u n c t i o n n a m ed inet_addr c o n v e r t s a d o t t e d I P a d d r e s s t o a 3 2 - b i t

    un s igned long in teger quant i t y . The inet_addr funct ion is def ined as

    unsigned long inet_addr(

    const char FAR *cp

    );

    T h e cp f i el d i s a n u l l - t er m i n a t ed c h ar a ct e r s t r i n g t h a t a cc ep t s a n I P a d d r e ss i n d o t t e dnot a t ion . Note that th i s funct ion re t ur ns an IP address as a 32-b i t u ns igned long in teger i nn e t w o r k - b y t e o r d e r .

    B y t e O r d e r i n g

    Di f f er e n t co m p u t e r p r o ces so r s r e p r e se n t n u m b e r s i n b i g -e n d i an an d l i t t l e -e n d i an f o r m ,d e p e n d i n g o n h o w t h e y a r e d e si gn e d . F or ex a m p l e , on I n t e l x 8 6 p r o ce ss or s, m u l t i - b y t enu m bers are repr esented in l i t t l e -end ian for m : the by tes ar e order ed f rom least sign i f i cantt o m o st s ig n i f i ca n t . W h e n a n I P a d d r es s a n d p o r t n u m b e r a r e s p ec i f i ed a s m u l t i - b y t eq u a n t i t i e s i n a c o m p u t e r , t h e y a r e r e p r e se n t e d i n h o s t -b y t e o r d e r . Ho w ev e r , w h e n I Paddr esses and p or t nu m bers are spec i f ied over a netw ork , In ter net netw ork ing s tand ardss p ec i fy t h a t m u l t i - b y t e v a l u es m u s t b e r e pr ese n t e d i n b i g -e n d i an f o r m ( m o st s ig n i f i ca n tby t e to least s ign i f i cant) , norm a l l y re fer r ed to as netw ork -by te or der .

    A ser ies o f funct ions can be used to conver t a m u l t i -by te nu m ber f r om host-by te ord er to

    n e t w o r k - b y t e o r d e r a n d v i c e v er s a . T h e f o l l o w i n g f o u r A P I f u n c t i o n s c o n v e r t a n u m b e rf r o m h o st - b y t e t o n e t w o r k - b y t e or d er :

    u_long htonl(u_long hostlong);

    int WSAHtonl(SOCKET s, u_long hostlong, u_long FAR * lpnetlong);

    u_short htons(u_short hostshort);

    int WSAHtons(SOCKET s, u_short hostshort, u_short FAR * lpnetshort);

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    5/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    Th e next four funct ions are the oppos i te o f the preced ing four funct ion s; they conver tnetw or k-by t e or der to host -by te ord er .

    u_long ntohl(u_long netlong);

    int WSANtohl(SOCKET s, u_long netlong, u_long FAR * lphostlong);

    u_short ntohs(u_short netshort);

    int WSANtohs(SOCKET s, u_short netshort, u_short FAR * lphostshort);

    Th e fo l low in g code dem onstr ates how to addr ess IPv4 by creat in g a SOCKADDR_IN s t r u c t u r eus ing the inet_addr an d htons funct ions descr ib ed pr ev ious ly .

    SOCKADDR_IN addr;

    int nPortId = 80;

    addr.sin_family = AF_INET;

    // Convert the proposed dotted Internet address 136.149.3.29

    // to a four-byte integer, and assign it to sin_addr

    addr.sin_addr.s_addr = inet_addr("136.149.3.29");

    // The nPortId variable is stored in host-byte order. Convert

    // nPortId to network-byte order, and assign it to sin_port.

    addr.sin_port = htons(nPortId);

    Cr eat in g Socket s

    T h e p r o t o t y p e f o r t h e socket funct ion is as fo l low s:

    SOCKET socket(int af, int type, int protocol);

    T h e f i r s t p a r a m e t er , af, i s t he pr o toco l 's addr ess fam i l y . Since w e ar e w ork ing on IPv4pr otoco l , w e shou ld set t h is f ie ld t o AF_INET. The second param eter , type, i s the pr o toco l 'ssocket ty pe. W hen w e ar e creati ng a socket t o use TCP/ IP, w e set t his f i eld t o SOCK_STREAM,

    and for UDP/ IP w e use SOCK_DGRAM. The th i r d parameter i s protocol and is used to qu al i fy

    a spec i f i c t ran spor t i f t here are m u l t ip le ent r ies fo r the g iven addr ess fam i l y and sockett yp e. For T CP w e shou ld set t his f ield t o IPPROTO_TCP; for UDP w e use IPPROTO_UDP.

    Unbound Socket

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    6/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    No w th at a socket is created, based on t he pr oto col the socket w as cr eated, w e can ei th er ofth e fo l low ing : connect t o a r emot e host (T CP), l i s ten a connect ion on a spec i f i c por t (TCP)or send data to a r em ote h ost w i t hout connect ing ( UDP). As an exam p le , le t s c reate a

    W in sock c l ient / serv er app l icat ion .

    A server i s a process that w a i ts fo r any n um ber o f c l ien t connect ions w i th the p urp ose o fserv ic ing the i r requ ests . A server m ust l i sten fo r connect ions on a w e l l -kn ow n nam e. InTCP/ IP, th is name is the IP addr ess of t he local int erface and a po rt num ber . Every p r otocolhas a d i f fe rent addr ess ing scheme and there for e a d i f fe rent nam ing m e thod. The f i r st s tepi n W i n so ck i s t o c r e at e a so ck e t w i t h t h e socket c a l l a n d b i n d t h e s o c k e t o f t h e g i v e npr o toco l to i ts w e l l -kn ow n name, w h ich i s accom p l i shed w i th the bind API cal l . The nexts t e p i s t o p u t t h e s oc k et i n t o l i st e n i n g m o d e , w h i c h i s p e r f o r m e d ( a p p r o p r i at e l y e n o u gh )

    w i th the listen API fun ct ion . F inal ly , w hen a c l ient attem pt s a conn ect ion, the server m ustaccept th e con nect ion w i t h the accept cal l .

    B i n d i n g

    O n ce t h e s ock e t o f a p a r t i c u l ar p r o t o c o l i s cr e a t e d , w e m u s t b i n d i t t o a w e l l- k n o w naddr ess. The bind funct ion assoc ia tes the g iven socket w i t h a w e l l -k now n addr ess. Th isfun ct ion is declar ed as

    int bind(

    SOCKET s,

    const struct sockaddr FAR* name,

    int namelen

    );

    Th e f i rs t param eter , s, is th e sock et on w hich w e w ant to w ai t f or c l ient connect io ns. Th esecond parameter i s o f type struct sockaddr, w hich is s im ply a generic b uffer . W e m ustactua l l y f i l l ou t an address buf fer spec i f i c to th e pr o toco l w e are us ing and cast t ha t as a

    struct sockaddr w hen cal l ing b ind . The th i r d param eter i s sim ply t he size o f the pr o toco l -

    Clien t/ Serve r Architecture

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    7/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    speci f ic address structure being passed. The fo l low ing code snippet creates a TCP socketand bi nds i t t o a w el l -kno w n addr ess ( I P + por t) .

    SOCKET s;

    SOCKADDR_IN addr; // == struct sockaddr addr;

    int port = 80;

    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    addr.sin_family = AF_INET;

    addr.sin_port = htons(port);

    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(s, (SOCKADDR *)&addr, sizeof(addr));

    Fr om th e code snip pet, w e l l see a str eam socket being cr eated, fo l low ed by sett ing up th e

    TCP/ IP addr ess s t ruc tur e on w h ich c l ien t connect io ns w i l l be accepted. In th is case, thesocket i s be ing bound to the defau l t IP in ter face by us ing a spec ia l address, INADDR_ANY( w hich m ean 0.0.0.0) , and occup ies por t nu m ber 80. W e could have specified an expl i ci t I Padd r ess avai lable on th e system , bu t INADDR_ANY al low s us to b ind to a l l avai lable in ter faceso n t h e s y s t e m s o t h a t a n y i n c o m i n g c l i e n t c o n n e c t i o n o n a n y i n t e r f a c e ( b u t t h e c o r r e c tp o r t ) w i l l b e a cce p t e d b y o u r l i st e n i n g s ock e t . T h e c al l t o bind fo rmal ly es tab l i shes th isassociat io n of t he socket w i t h th e local IP inter face and por t .

    O n e r r o r , bind r e t u r n s SOCKET_ERROR. The m ost com mo n err or encount ered w i th bind i sWSAEADDRINUSE. W it h T CP/ IP, t he WSAEADDRINUSE err or ind ica tes that another pr ocess i sa l ready bound t o the loca l IP in t er face and por t nu mb er or t ha t the IP in t er face and por t

    n u m b e r ar e i n t h e TIME_WAIT stat e. If w e call bind again on a socket th at is a l ready bo un d,WSAEFAULT w i l l be re tur ned.

    L is t e n in g

    Th e next step is to p ut t he socket in to l is t ening m ode. Th e bind funct ion merely associatesth e socket w i th a g iven addr ess. The API fu nct ion that te l l s a socket t o w a i t fo r incom ing

    connect ions i s listen, w h ich is d efin ed as

    int listen(

    SOCKET s,

    int backlog

    Bound Socket

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    8/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    );

    A ga in , t h e f i r st p a r am e te r i s a b o u n d so ck e t . T h e backlog p a r a m e t e r s p ec i fi es t h e

    m ax i m u m q u eu e l en g th f or p en d i n g c on n ect i o ns. T h i s i s i m p o r t an t w h en sev er als i m u l t a n eo u s r e q u e st s ar e m a d e t o t h e s er v e r . F or ex a m p l e , l et ' s sa y t h e backlog

    par am eter is set t o t w o. I f t hr ee cl ient r equests ar e m ade at t he sam e t im e, th e f i r st tw o w i l lbe p laced in a pend in g queue so th at th e app l i ca t ion can ser v ice the i r r equests . The th i rd

    conn ect ion r equest w i l l fa i l w i th WSAECONNREFUSED. Note that once the server accepts aconnect ion , th e r equest i s rem oved f r om the qu eue so t hat o t hers can m ake a request . The

    backlog p a r a m e t er i s si l e n t l y l i m i t e d t o a v a l u e t h a t t h e u n d e r l y i n g p r o t o c o l p r o v i d e rdeter m ines. I l legal valu es ar e rep laced w i t h t hei r nearest legal values. The fo l low ing codesnip pet m akes the socket cr eated abov e l is ten on th e speci f ied po rt .

    listen(s, 5); // where 5 is the maximum pending connections

    Th e er r or s associated w i th listen ar e fa ir l y s t r a ight forw ard . By fa r the m ost com m on is

    WSAEINVAL, w hich usual ly i ndicates th at w e for got t o cal l bind b e f o r e listen.

    Accept ing

    No w w e 'r e r e ad y t o a cce p t c l i en t c o n n ec t i on s . T h i s i s a cc o m p l i sh e d w i t h t h e acceptfunct io n . The pro to typ e for accept i s

    SOCKET accept(

    SOCKET s,

    struct sockaddr FAR* addr,int FAR* addrlen

    );

    Parameter s i s the bou nd socket th a t i s in a l i s ten ing s ta te . The second p aram eter shou ld

    be th e addr ess of a val id SOCKADDR_IN st ruc tur e , w h i le addrlen should b e a r eference to

    t h e l e n gt h o f t h e SOCKADDR_IN st ruc t ur e . For a socket o f another pr o toco l , w e subst i t u te

    t h e SOCKADDR_IN w i th the SOCKADDR st ruc ture correspond ing to tha t p ro toco l . A ca l l to

    accept serv ices the f i rs t connect ion r equest in th e queue o f pend ing connect ions. W hen

    t h e accept f u n c t i o n r e t u r n s , t h e addr st ruc tu re conta ins the IPv4 addr ess in for mat i on o f

    th e cl ien t m ak ing the connect ion r equest , and th e addrlen param eter in dicates th e s ize of

    Listening Socket

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    9/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    t h e s t r u c t u r e . I n a d d i t i o n , accept r e tur ns a new socket descr ip tor tha t corr esponds to theaccepted c l ien t conn ect ion . For a l l subsequent opera t ion s w i th th is c l ien t , the new socketshould be used. The or ig inal l is tenin g socket is st i l l open to accept ot her c l ient con nect ion s

    and is st i l l i n l i s ten ing m ode.

    I f an er ror occur s , INVALID_SOCKET i s re tur ned. The m ost com m on er ror encount ered i s

    WSAEWOULDBLOCK i f t h e l i s t en i n g s o ck e t i s i n a sy n c h r o n o u s o r n o n - b l o ck i n g m o d e a n dth ere is no connect ion to be accepted .

    Th e fo l low in g pr ogram fr agment dem onstr ates a s im ple server th at accepts one TCP/ IPconnect ion .

    Client Atte m pting to Connect on the Listen ing port (80 )

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    10/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    #include

    void main(void)

    {

    WSADATA wsadata;SOCKET sock;

    SOCKET new_sock;

    SOCKADDR_IN server_addr;

    SOCKADDR_IN cleit_addr;

    int port = 80;

    // Initialize Winsock version 2.2

    WSAStartup(MAKEWORD(2,2), &wsadata);

    // Create a new socket to listen for client connections.

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    // Set up a SOCKADDR_IN structure that will tell bind that we

    // want to listen for connections on all interfaces using port

    // 80. Notice how we convert the port variable from host byte

    // order to network byte order.

    server_addr.sin_family = AF_INET;

    server_addr.sin_port = htons(Port);

    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    // Associate the address information with the socket using bind.

    bind(sock, (SOCKADDR *)&server_addr, sizeof(server_addr));

    // Listen for client connections. We used a backlog of 5, which

    // is normal for many applications.

    listen(sock, 5);

    // Accept a new connection when one arrives.

    new_sock = accept(sock, (SOCKADDR*)&client_addr,& client_addr));

    // At this point we can do two things with these sockets. Wait

    // for more connections by calling accept again on sock

    // and start sending or receiving data on new_sock.

    // When we are finished sending and receiving data on the

    // new_sock socket and are finished accepting new connections

    // on sock, we should close the sockets using the

    // closesocket API.

    closesocket(new_sock);

    closesocket(sock);

    // When our application is finished handling the connections,

    // we call WSACleanup.

    WSACleanup();

    }

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    11/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    Not e that the above f ragment does not invo lve er r or hand l in g . Now that w e have seen th eserver s id e of c l ient/ server ar chi t ectur e, let s now see th e c l ient s ide.

    Connect ing

    Connect ing a socket i s accom p l i shed by ca l ling th e connect funct ion . T h e p r o t o t y p e f o rconnect is as fol lo w s

    int connect(

    SOCKET s,

    const struct sockaddr FAR* name,

    int namelen

    );

    Th e param eters are fa i r l y se l f -exp lanator y : s is the v al id T CP socket o n w hich to establ ish

    the connect ion , name i s the socket addr ess s t ruc t ur e ( SOCKADDR_IN) fo r TCP that descr ib esth e ser ver t o con nect to, and namelen is th e length o f the name var iab le .

    I f t he com pu ter w e ' re a t tem pt in g to connect t o d oes not h ave a pr ocess l i s ten ing on the

    g iven por t , the connect cal l fa i ls w i th th e WSAECONNREFUSED err or . The o ther er r or w e m ighte n co u n t e r i s WSAETIMEDOUT, w h i ch o cc u r s i f t h e d e st i n a t io n w e 'r e t r y i n g t o r e ac h i sun avai lab le (e i ther b ecause o f a com m unicat ion-har dw are fa i lu re on t he ro ute t o th e hostor because the host i s no t cur rent ly on t he netw ork ) .

    A Connected Socket

    Th e fo l low ing pr ogram f ragment demon str a tes a c l ien t connect ing to a server l i s ten ing onp o r t 8 0 .

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    12/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    #include

    void main(void)

    {

    WSADATA wsadata;SOCKET s;

    SOCKADDR_IN server_addr;

    int port = 80, status;

    // Initialize Winsock version 2.2

    WSAStartup(MAKEWORD(2,2), &wsadata);

    // Create a new socket to make a client connection.

    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    // Set up a SOCKADDR_IN structure that will be used to connect

    // to a listening server on port 80. For demonstration// purposes, let's assume our server's IP address is 192.168.0.8.

    // Obviously, we will want to prompt the user for an IP address

    // and fill in this field with the user's data.

    server_addr.sin_family = AF_INET;

    server_addr.sin_port = htons(port);

    server_addr.sin_addr.s_addr = inet_addr("192.168.0.8");

    // Make a connection to the server with socket s.

    status = connect(s, (SOCKADDR *)&server_addr, sizeof(server_addr));

    if (status == 0)

    {// now were connected, do sending and receiving here

    }

    // When we are finished sending and receiving data on socket s,

    // we should close the socket using the closesocket API.

    closesocket(s);

    // When our application is finished handling the connection, call

    // WSACleanup.

    WSACleanup();

    }

    W e h a v e se en h o w t o s et u p a se r v e r a n d h o w t o m a k e a c o n n ec t i o n t o a se r v e r f r o m ac l ien t us ing C. But w e haven t done anyth ing o th er than h andshak i ng so far . Le t s now seeho w w e can hand le data tr ansm ission .

    D a t a T r a n s m i ssi o n

    Send ing and r eceiv in g data is w hat n etw or k pr ogram m ing is a l l about. For sendin g data on

    a conn ected socket w e u se the send funct ion . L ikew ise, w e use t he recv f u n c t i o n f o rr eceiv in g data on a conn ected socket.

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    13/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    S e n d in g

    Th e API funct ion t o send data on a con nected socket is send, w hich is pr ot oty ped as

    int send(

    SOCKET s,

    const char FAR * buf,

    int len,

    int flags

    );

    T h e SOCKET p a r am e t er i s t h e c on n ec t ed so ck e t t o se n d t h e d at a o n . T h e s ec on d

    p a r a m e t e r , buf, i s a po in ter t o th e character buf fer tha t cont a ins the data to be sent . The

    t h i r d p a r am e t er , len, speci f ies th e num ber of character s in th e bu ffer t o send. Final ly , th e

    flags par am eter can b e ei t her 0, MSG_DONTROUTE, o r MSG_OOB. A l te rn at ive ly , the f lags

    p a r a m e t e r ca n b e a b i t w i se OR any o f those f lags. The MSG_DONTROUTE f l ag te l l s thet r anspor t no t t o rout e the packets i t sends. I t i s up to t he under ly in g t r anspor t to honor th isr eq u e st ( f o r ex am p l e, i f t h e t r a n sp o r t p r o t oco l d o esn ' t su p p o r t t h i s o p t i o n , i t w i l l b e

    ignor ed) . The MSG_OOB f lag s igni f ies that t he data should be sent ou t of band .

    O n a g o o d r e t u r n , send r e t u r n s t h e n u m b e r o f b y t e s se n t ; o t h e r w i se , i f a n e r r o r o cc u r s ,

    SOCKET_ERROR w i l l be r e tur ned. A com m on er r or i s WSAECO-NNABORTED, w hich occursw hen th e v i r t ua l ci rcu i t te r m inates because o f a t im eout fa i lu re or a pro t oco l e r ror . W henth is occur s, the socket shou ld b e c losed, as i t is no lon ger usable.

    R e c e iv in g

    T h e recv fun cti on is th e m ost b asic w ay to accept in com ing dat a on a conn ected socket .Th is funct io n i s defined as

    int recv(

    SOCKET s,

    char FAR* buf,

    int len,

    int flags

    );

    T h e f i r s t p a r a m e t e r , s, is the socket on w hich d ata w i l l b e received. Th e second p aram eter ,buf, is th e char acter bu ffer t hat w i l l r eceive th e data, and len is e i th er t he num ber of by tes

    w e w ant t o r eceive or th e s ize of the bu ffer, buf. F inal ly , th e flags param eter can be one

    of t he fo l lo w ing valu es: 0, MSG_PEEK, o r MSG_OOB. In addi t i on, w e can b i tw ise OR any one

    of th ese f lags togeth er . Of cour se, 0 specifies no special actions. MSG_PEEK causes th e datath at i s ava i lab le to be cop ied in to the supp l ied r ece ive buf fer , bu t th is data i s not r emov edfr om the system 's buf fer . The num ber o f by tes pend ing i s also re tur ned.

    A str eam ing pr ot ocol is one th at th e send er and r eceiver m ay br eak up or coalesce dat a intosmal le r o r la rger group s. The m ain th ing to be aw are o f w i th any fu nct ion that sends or

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    14/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    r eceives data on a str eam socket is that w e are no t guaran teed to r ead or w r i te th e am ountof d ata w e request. The fo l l ow ing code sni ppets ensur e that a l l our by tes are ei th er sent orrece ived.

    // Make sure everything is sent

    char sendbuff[2048];

    int nBytes = 2048, nLeft, idx;

    // Fill sendbuff with 2048 bytes of data

    // Assume s is a valid, connected stream socket

    nLeft = nBytes;

    idx = 0;

    while (nLeft > 0)

    {

    ret = send(s, &sendbuff[idx], nLeft, 0);if (ret == SOCKET_ERROR)

    {

    // Error

    }

    nLeft -= ret;

    idx += ret;

    }

    // we are done sending.

    // Make sure everything is received

    char recvbuff[1024];int ret, nLeft, idx;

    nLeft = 512; // say, we expect a 512byte of data

    idx = 0;

    while (nLeft > 0)

    {

    ret = recv(s, &recvbuff[idx], nLeft, 0);

    if (ret == SOCKET_ERROR)

    {

    // Error

    }

    idx += ret;

    nLeft -= ret;}

    // we are done receiving.

    B r e a k in g t h e Co n n e ct io n

    Once w e are f in ished w i th a socket con nect ion, w e m ust c lose i t and r elease any r esour cesassocia ted w i th tha t socket hand le . To actua l l y re lease t he resources assoc ia ted w i t h anopen socket hand le , w e use t he closesocket cal l . W e should be aw are, ho w ever, t hat

    closesocket can have some adverse e f fects depending on how i t i s ca lled that can

    Receiving snippe t

    Sendin g snipp et

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    15/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    l ead to data loss . For th is r eason, a connect ion shou ld be gracefu l l y te r m inated w i th the

    shutdown funct ion before a ca l l to th e closesocket f u n c t i o n .

    T o en s ur e t h at a ll d a t a a n a p p li cat i o n s en d s i s r ec ei v ed b y t h e p e er , a w e ll -w r i t t e napp l i ca t ion shou ld n ot i fy the r ece iver tha t no m or e data i s t o be sent . L ikew ise , the peershou ld do the sam e. Th is i s k now n as a gracefu l c lose and i s per for m ed by the shutdownfunct io n , de fined as

    int shutdown(

    SOCKET s,

    int how

    );

    T h e how p a r a m e t er c an b e SD_RECEIVE, SD_SEND, o r SD_BOTH. F o r SD_RECEIVE,subsequent cal ls to any receive funct ion o n t he sock et are di sallow ed. Th is has no effect on

    t h e l o w er p r o t o co l l a y e r s . A n d f o r T CP s oc k et s , i f d a t a i s q u e u e d f o r r e ce iv e o r i f d a t asubsequent ly ar r i ves, the connect ion i s r eset . How ever , on UDP sockets incomi ng data i s

    s t i l l a cc ep t e d a n d q u e u ed ( b e ca u se shutdown h as n o m e a n i ng f o r c on n ec t i on l ess

    pr o toco ls) . For SD_SEND, subsequent ca ll s to any send funct ion are d isa llow ed. For TCP

    socket s, th is causes a FIN packet to b e generated aft er a l l data is sent and ackn ow ledged by

    th e receiver. Final ly , speci fy i ng SD_BOTH disables bo th sends and r eceives.

    Not e that no t a l l connect ion-or ien ted pr o toco ls supp or t g r acefu l c losur e , w h ich i s w hat t heshutdown API per for m s. For t hese pr otocols (such as ATM ) , on ly closesocket needs tobe cal led to ter m in ate the session.

    Clo sing a Sock et

    T h e closesocket funct ion c loses a socket and is def ined as

    int closesocket (SOCKET s);

    Cal l ing closesocket r e leases the socket descr ip tor and any fur ther cal l s us ing the socketf a i l w i t h WSAENOTSOCK. I f t h er e ar e n o o t h er r e f er e n ce s t o t h i s s oc k et , a l l r eso u r c esassociated w i th th e descr ipt or are r e leased. Th is includes discard ing any qu eued data.

    Conn ect ion less Com m un icat ion

    Co nn ect io n less co m m u n icat io n b eh av es d i ffe r en t ly t h an co n nec ti on -o r i en t edcom m unicat ion , so t he m ethod for send in g and r ece iv ing data i s substant ia l l y d i f fe rent . InIP, connect io nless com m un icat ion is accom pl ished t hr ough UD P/ IP. UDP doesn't guar ant eer e li ab l e d a t a t r a n sm i ss io n a n d i s c a p ab l e o f s en d i n g d a t a t o m u l t i p l e d e st i n a t i o n s a n dr eceiv in g i t f r om m ul t ip le sour ces. For exam ple, i f a cl ient send s data to a ser ver , th e data ist r a n sm i t t e d i m m e d i at e l y r eg ar d l e ss o f w h e t h e r t h e s er v e r i s r ea d y t o r e c ei v e i t . I f t h eserver r eceives data fr om th e c lient , i t d oesn't acknow ledge the receipt . Data is tr ansm i t tedusin g datagram s, w hich are d iscr ete m essage packets.

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    16/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    A UDP socket i s cr eated as fol lo w s:

    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    Receiv ing on Conn ect ionless Com m un icat ion

    Th e steps in th e pr ocess of r eceiv in g data on a con nect ion less socket ar e sim ple. F i r st , w ecreate the socket w i th e i ther . Next , b ind the socket to the in t er face on w h ich w e w ish to

    r ec ei v e d a t a. T h i s i s d o n e w i t h t h e bind f u n c t i o n ( e x ac t l y l i k e t h e s essi o n - o r i e n t e de x am p l e ) . T h e d i f f e r e n ce w i t h c o n n ec t i o n l ess so ck e t s i s t h a t w e d o n o t ca l l listen oraccept. I n s t ea d , w e si m p l y w ai t t o r e cei v e t h e i n co m i n g d a t a. B ec au se t h er e i s n oconnect ion , the rece iv ing socket can r ece ive datagr am s or ig inat ing f ro m any m ach ine onth e netw or k. The s im plest of th e receive fun ct ion s is recvfrom, w h ich is d efin ed as

    int recvfrom(

    SOCKET s,

    char FAR* buf,

    int len,

    int flags,

    struct sockaddr FAR* from,

    int FAR* fromlen

    );

    Send ing on Conne ct ion less Com m un icat ion

    Th e sim plest w ay to send dat a on a connect ionless com m un icat ion i s to create a UDP

    socket and cal l sendto w hich is def ined as

    int sendto(

    SOCKET s,

    const char FAR * buf,

    int len,

    int flags,

    const struct sockaddr FAR * to,

    int tolen

    );

    Usefu l API s

    W e have covered som e o f the genera l APIs needed t o c r eate a c l ien t / serv er e i th er on aconnect ion-or ien t ed or connect i on less comm un icat ion . Le t s now d iscuss som e com m onuseful APIs.

    getp eer na m e

    Th is fun ct io n is used to obt ain th e peer 's socket addr ess in for m ation on a conn ected sock et.Th e funct ion is def ined as

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    17/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    int getpeername(

    SOCKET s,

    struct sockaddr FAR* name,

    int FAR* namelen

    );

    Th e f i rs t par ameter i s the sock et fo r the connect ion ; the last t w o param eters ar e a po in tert o a SOCKADDR s t r u c t u r e o f t h e u n d e r l y i n g p r o t o c o l t y p e a n d i t s l e n g t h . F o r d a t a g r a msock ets, th is fun ct ion r etu r ns th e addr ess passed t o a connect ca l l ; how ever , i t w i l l n o tr etur n the addr ess passed to a sendto cal l .

    getsockna m e

    T h i s f u n c t i o n i s t h e o p p o s i t e o f getpeername. I t r e t u r n s t h e a d d r e ss i n f o r m at i o n f o r t h elocal int er face of a g iven sock et. Th e funct i on i s def ined as fo l low s:

    int getsockname(

    SOCKET s,

    struct sockaddr FAR* name,

    int FAR* namelen

    );

    T h e p a r a m et e r s a r e t h e sa m e a s t h e getpeername p a r a m e t e r s e x c e p t t h a t t h e a d d r e s si n f o r m a t i o n r e t u r n e d f o r s oc k et s is t he local addr ess info rm at ion . In th e case of TCP, th eadd r ess is th e sam e as the ser ver socket l i s tening on a speci f ic por t and I P inter face.

    geth ostbyn a m e

    Th is funct io n t r ansla tes a hostname to i t s netw ork I Pv4 addr ess. I t s p r o to ty pe i s

    HOSTENT gethostbyname(const char FAR * hostname);

    Th e param eter hostname is the nam e of the host w e w ant t he IP for .

    Conclusion

    In th e abov e discussion, w e have seen cor e W insock APIs that are r equi r ed for conn ect ion-or ien ted and connect ion less com m un icat ion spec i f i ca l l y us ing t he TCP and UDP pr o toco ls .For connect ion -or ien ted com m un icat ion , w e have seen how to accept a c l ien t connect ionand how to estab l i sh a c l ien t connect ion to a server . W e have a lso seen t he semant ics fo rsession-or ien ted data-send opera t ions and data- rece ive oper a t ions. For connect ion lesscom m un icat ion , w e have seen h ow to send and r eceive data. The W ind ow s Socket A PI hasnu m erous usefu l funct ion s to w or k on netw ork pr ogram ing. I have t r i ed to go th r ough them ost im por tant APIs to per for m s im p le netw ork com m un icat ion . The accom pany ing chatpr ogram s ( CS461 Chat Cl ient an d Serv er pr ogram s) dem onstr ate the concept s d iscussed inth is assignmen t . The chat p rogram is a m ul t i t h r eaded p rogr am w r i t ten ent i re ly in C. V isua lC 6 .0 ( par t o f t he V isua l Stu d io 6 .0 su i te , 1998) i s needed t o com p i le t he code. The o th erp l a t f o r m s ( .NE T w i t h C# o r V B , V B 6 ) h i d e m o st o f t h e u n d e r t h e h o o d c o n ce p t s ab o u t

  • 7/23/2019 Windows Socket Programming in C - Biniam Fisseha

    18/18

    CS4 6 1 : N e t w o r k W i n d o w s So c k e t Pr o g r a m m i n g i n C B i n i a m F i s se h a

    sock et p r ogram m ing and for tha t r eason I ha te them . In add i t ion to t ha t the advantage w i thC is tha t w e can d i r ect l y ta lk to the APIs the oper a t ing sys tem pr ov ide. W hen d eal ing w itht h e o t h er f r a m e w o r k s , t h ey n o r m a ll y p r o v i d e an i n t er f ace t o t h e A PI . T h e r ef o r e o u r

    app l i ca t ion needs to inc lude the f r am ew or k DLL in the ins ta l la t ion package. For exam p le ,V isua l Basic 6 .0 pr ov ides an in t er face to the W ind ow s Socket API (w s2_32.d l l fu nct ions)th r ough M SW INSCK.OCX Act iveX Contr o l . That m eans, in or der to m ake our app l i cat ionw or k, w e need to inclu de th is OCX in th e distr ibu t io n. Note also th at w e can actual ly w r i te aW in sock appl icat i on w i th VB 6 that does not u se the M SW IN SCK.OCX Act iv eX Contr ol . Bu t i tneeds too m uch effor t and w e w i l l no t escape fr om the M SVBVM 6.0.DLL l ib r ary , th e VisualBasic 6 Run tim e Libr ary , w hich i s not guar anteed t o exist on W ind ow s versions earl ier th an20 00 and i t i s ar ound 2M B in s ize, w h ich m ight be a headache for d is t r ibu t ion t h r ough th eIn t ernet . But in C, w e have the luxur y o f w r i t ing a n eat and l igh t w e ighted app l i cat ion thatdoes not need any add i t iona l l i b rar y o th er th an the C Runt im e L ibr ary w h ich i s guaranteedto exist on ever y W ind ow s system because th e W in do w s oper at in g system i t sel f re l ies on i t .