9.0

Table Of Contents
VMware, Inc. 27
Appendix: Learning More About Sockets
InthesockaddrstructureforIPv4sockets,thefirstfieldspecifiesAF_INET.Thesecondfieldsin_portcan
beanyinteger>5000.Lowerportnumbersarereservedforspecificservices.Thethirdfieldin_addristhe
Internetaddressindottedquadnotation.Fortheserver,youcanusetheconstantINADDR_ANYtotellth
e
systemtoacceptaconnectiononanyInternetinterfaceforthesystem.Conversionfunctionshtons()and
htonl()areforhardwareindependence.Forexample:
#define SERV_PORT 5432
struct sockaddr_in serv_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERV_PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
Listen() System Call
Thelisten()systemcallpreparesaconnectionorientedservertoacceptclientconnections.
int listen(int sockfd, struct <backlog>);
Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd.
Thesecondparameterspecifiesthenumberofrequeststhatthesystemqueuesbeforeitexecutesthe
accept() systemcall.Higherandlowervaluesof<backlog>tradeoffhighefficiencyforlowlatency.
Forexample:
listen(sockfd, 5);
Accept() System Call
Theaccept()systemcallinitiatescommunicationsbetweenaconnectionorientedserverandtheclient.
int accept(int sockfd, struct sockaddr *cli_addr, int addrlen);
Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd.
Thesecondparameteristheclient’ssockaddraddress,tobefilledin.
Thethirdparameteristhelengthoftheclient’ssockaddrstructure.
Generallyprogramscallaccept()insideaninfiniteloop,forkinganewprocessforeachacceptedconnection.
Afteraccept()returnswithclientaddress,theserverisreadytoacceptdata.
Forexample:
for( ; ; ) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, sizeof(cli_addr));
if (fork() = 0) {
close(sockfd);
/*
* read and write data over the network
* (code missing)
*/
exit (0);
}
close(newsockfd);
}
Connect() System Call
Ontheclient,theconnect()systemcallestablishesaconnectiontotheserver.
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);
Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd.
Thesecondparameteristheserverssockaddraddress,tobefilledin.
Thethirdparameteristhelengthoftheserverssockaddrstructure.