Network Programming usingsocketsDistributed Software SystemsProf. Sanjeev SetiaAPIs for TCP/IPTCP/IP is a proto col designed to op erate in multi-vendor environmentinterface between TCP/IP and applications lo oselysp eciedapplication interfaces{BSD UNIX:so cketinterface{AT&T:TLIinterfaceTCP/IP software inside kernel invoked by systemcallsUNIX I/O facilities extended with TCP/IP sp eciccalls9The So cket Interfaceprovides functions that supp ort networkcommunication using many p ossible proto cols{PFINET is one proto col family supp orted byso ckets{TCP and UDP are proto cols in PFINET familyso cketis the abstraction for network communicationa so cket is identied by so cket descriptorsystem data structure for so cket{family (e.g., PFINET){service (e.g., SOCK STREAM){Lo cal IP address, Lo cal Port{Remote IP address, Remote Portpassiveso cket: so cket used by a server to wait forincoming connections ;activeso cket: so cket usedby client to initiate a connection10Endp oint AddressesTCP/IP proto cols dene a communication endp ointto consist of an IP address and a proto col portnumb erother proto col families have other denitionsso cket abstractions supp orts the concept ofaddressfamilywhich allows dierent proto cols to have theirown address representationsTCP/IP proto cols use a single addressrepresentation with address family denoted byAFINET11Endp oint Addresses cont'dstructure for AFINET addressesstruct sockaddr_in { /* struct to hold an address */u_char sin_len; /* total length */u_short sin_family; /* type of address */u_short sin_port; /* protocol port number */struct in_addr sin_addr; /* IP address */char sin_zero[8]; /* unused (set to zero) */};if program using mixture of proto cols, programmer must be careful sincenot all addresses have the same size12System Callsso cket{used to create new so cket{arguments: proto col family (e.g. PFINET),proto col or service (i.e., stream or datagram){returns so cket descriptorconnect:{client calls connect to establish an activeconnection to the server{argument to connect sp ecies remote endp ointwrite{servers and clients use write to send data acrossa TCP connection{arguments: so cket descriptor, address of data,length of data13System Calls cont'dread{used to receive data from a TCP connection{arguments: so cket, buer, length of buer{read blo cks if no data; if more data than ts inbuer, it only extracts enough to ll the buer;if less than buer length, it extracts all the dataand returns numb er of bytes readread and write can also be used with UDP butdierent b ehaviorclose: used to deallo cate so cket; deleted when lastpro cess that is using so cket do es a closebind{used to sp ecify a lo cal endp oint address for aso cket{uses so ckaddrin structure14System Calls cont'dlisten{used by connection-oriented servers to put so cketin passive mo de{arguments: so cket, size of queue for so cketconnection requestsaccept{creates a new so cket for each connection request{returns descriptor of new so cket to its calllerUDP calls:{send, sendto, sendmsg{recv, recvfrom, recvmsg15Integer Conversionstandard representation for binary integers used inTCP/IP proto col headers:network byte order, MSBrste.g. the proto col port eld in struct so ckaddrinuses network byte orderhost's integer representation mayb e dierentconversion routines: htons, htonl, ntohl, ntohsshould be used for portability16Client Softwareconceptually simpler than servers b ecausedo not have to handle concurrent interactions withmultiple serversusually not privileged software)don't have to beas carefulno authentication, protection, etc.17Lo cating the serverserver's IP address and port numb er neededcan be sp ecied as a constant in the programhave the user sp ecify it as an argument wheninvoking clientread from a le on diskuse a proto col to nd the server (e.g. a broadcastmessage to which servers resp ond)18Parsing address argumentaddress argument typically is a hostname likecs.gmu.edu or IP address in dotted decimal notationlike 129.174.29.34need to sp ecify address using structure so ckaddrinlibrary routines inetaddr and gethostbyname usedfor conversionsstruct hostent {char *hname;char **h_aliases;int h_addrtype;int h_length;char **h_addr_list;};#define h_addr h_addr_list[0];19EXAMPLE:struct hostent *hptr;char *name = ``cs.gmu.edu'';if ( hptr = gethostbyname(name)) {/* IP address is in hptr->h_addr */} else {/* handle error */}inetaddr converts dotted decimal IP address intobinary20Client Software cont'dlo oking up a well known port by namestruct servent dened innetdb.hin the same way as structhostentstruct servent *sptr;if (sptr = getservbyname(``smtp'',``tc p'')){/* port number is now in sptr->s_port */} else {/* handle error */}NOTE: getservbyname returns proto col port innetwork byte order21Client Software cont'dlo oking up a proto col by namestruct proto ent dened innetdb.hstruct protoent *pptr;if (pptr = getprotobyname(``udp'')){/* official protocol number is in pptr->p_proto */} else {/* handle error */}22TCP client algorithm1. Find IP address and proto col numb er of server2. allo cate a so cket3. sp ecify that the connection needs an arbitrary,unused proto col port on lo cal machine and allowTCP to select one4. Connect the so cket to the server5. Communicate with the server using application-levelproto col6. Close the connection23TCP client cont'dAllo cating a so cket#include <sys/types.h>#include <sys/socket.h>int s; /* socket descripto */s = socket(PF_INET,SOCK_STREAM, 0);Cho osing a lo cal port numb er{conicts have to be avoided{happ ens as a side-eect to connect callcho osing a lo cal IP address{a problem for hosts connected to multiplenetworks{chosen automatically by TCP/IP at time ofconnection24Connecting a TCP so cket to a serverretcode = connect(s,remaddr,re maddrlen)connect p erforms four tasks1. tests sp ecied so cket is valid and not alreadyconnected2. lls in remote address in so cket from secondargument3. cho oses a lo cal endp oint address for so cket (if itdo es not have one)4. initiates a connection and returns value to thecaller25Communicating with the server usingTCP: Example#define BLEN 120char *req = ``request of some sort'';char buf[BLEN];char *bptr;int n;int buflen;bptr = buf;buflen = BLEN;/* send request */write(s,req,strlen(req);/*
View Full Document