











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!












TCP Server
TCP Client
Well known port
Blocks until connection from client
Data
Data
End of Data Indication
#include <sys/socket.h>
int bind (int sockfd, const struct sockaddr *myaddr, socklen_t addrlen); Returns: 0 if OK, -1 on error
Returns:0 if OK, -1 on error
==>This function is called only by a TCP server
Returns:nonnegative descriptor if OK, -1 on error
pid_t pid
int listenfd, connfd;
listenfd = Socket(...);
//fill in sockaddr_in{} with server’s well-known port
Bind(listenfd, LISTENQ);
for(;;){
connfd = Accept(listenfd, ...); doit(connfd); //process the request Close(); //done with this client exit(0); //child terminate } Close(connfd); // parent close connected socket
}
Outline for typical concurrent server
returns:0 if OK, -1 on error
getsockname and getpeername
function
both return : 0 if OK, -1 on error
=>getsockname : return local address associated with a socket
getpeername : foreign protocol address associated with a socket
#include "unp.h"
int sockfd_to_family(int sockfd) { union { struct sockaddr sa; char data[MAXSOCKADDR]; } un; socklen_t len;
len = MAXSOCKADDR; if (getsockname(sockfd, (SA *) un.data, &len) < 0) return(-1); return(un.sa.sa_family); }