100 likes | 237 Views
Socket Programming Review. Examples: Client and Server-Diagnostics UDP versus TCP Echo. Socket Interface-an Application Programming Interface (API). Create the Socket for a specific transport layer protocol s=socket(PF_INET,SOCK_STREAM,0) or s=socket(PF_INET,SOCK_DGRAM,0)
E N D
Socket Programming Review Examples: Client and Server-Diagnostics UDP versus TCP Echo Datacom 1
Socket Interface-an Application Programming Interface (API) Create the Socket for a specific transport layer protocol • s=socket(PF_INET,SOCK_STREAM,0) or • s=socket(PF_INET,SOCK_DGRAM,0) returned value is a “handle” e.g. 3,4 etc. PF_INET: SOCK_STREAM means TCP: 1 client/server SOCK_DGRAM means UDP: multi-clients/server Datacom 1
Data structures: hostent *hp • hp->h_name (character) contains host name • hp->h_length number of bytes in IP address • hp->h_addr[4] contains IP address • byte1:byte2:byte3:byte4 • A.B.C.D 0<A,B,C,D<255 • 127.0.0.1 is address of localhost or loop-back address Datacom 1
Data structures: sockaddr_in sin • sin.sin_family AF_INET • sin.sin_addr.s_addr IP address in reverse byte order DCBA • 1.0.0.127 is address of localhost or loop-back address • sin.sin_port Server port number in some strange format Datacom 1
Socket Interface: Server (a) • Creating socket • s=socket(PF_INET,SOCK_STREAM,0) • Binding a Socket to a Port Number—this is the local address of this application • bind (s, (struct sockaddr*)&sin, sizeof(sin)) • The entry for IP address in sin.sin_addr.s_addr will be the client’s IP address—it cannot be specified until connection is accepted. Datacom 1
Socket Interface: Server (b) • Defining the queue length for the receiving socket • int listen(s, MAX_PENDING) • Specify max number of calls waiting • Passive listening • new_s= accept (s, (struct sockaddr*)&sin,&len) • Sender’s IP address is returned as sin.sin_addr.s_addr • New socket is created and its number is returned Datacom 1
Socket Interface: Server (c) • Receiving a message • recv(new_s, buf, sizeof(buf),0) • Receive message, store in buf • Closing new socket • close(new_s) Datacom 1
Socket Interface: Client (a) • Create a socket • s=socket(PF_INET,SOCK_STREAM,0) • Connecting to a server-active open • connect (s, (struct sockaddr*) &sin, sizeof(sin)) • Server’s IP address is stored in sin.sin_addr.s_addr • Server’s Port is stored in sin.sin_port • Returns accept or not accepted Datacom 1
Socket Interface: Client (b) • Sending message to a server • send(s, buf, len, 0) • buf is a pointer to the message • len is length of message string Datacom 1