The Sockets Library and Concepts Rudra Dutta CSC Spring 2007, Section 001
Copyright Rudra Dutta, NCSU, Spring API for Network Apps Interface between TCP/IP and applications only loosely specified The standards suggest the functionality (not the details) – allocate resources for communication – specify communication endpoints – initiate a connection (client) or wait for incoming connection (server) – send or receive data – terminate a connection gracefully – handle error conditions – etc.
Copyright Rudra Dutta, NCSU, Spring Unix File I/O Program calls open() to initiate input or output – returns a file descriptor (small, positive integer) Calls to read() or write() to transfer data – with the file descriptor as an argument Once I/O operations are completed, the program calls close() Other relevant system calls: lseek(), ioctl() – (these are not used in the Sockets API)
Copyright Rudra Dutta, NCSU, Spring Unix File I/O Example Roughly the same for sockets, except for setup int fd; char buf[256]; fd = open("a.txt", ORDWR | O_CREAT); write(fd, buf, sizeof(buf)); close(fd);
Copyright Rudra Dutta, NCSU, Spring Socket API Introduced in 1981 by BSD 4.1 – implemented as system calls – originally only Unix but WinSock almost the same Mainly, two services – datagram (UDP) – stream (TCP)
Copyright Rudra Dutta, NCSU, Spring The Socket Abstraction Provides an endpoint for communication – also provides buffering – sockets are not bound to specific addresses at the time of creation Identified by small integer, the socket descriptor Flexibility – functions that can be used with many different protocols – programmer specifies the type of service required, rather than the protocol number – a generic address structure
Copyright Rudra Dutta, NCSU, Spring Endpoint Addresses Each socket association has five components – protocol – local address – local port – remote address – remote port protocol: used by socket() local address, port: bind() remote address, port: connect(), sendto()
Copyright Rudra Dutta, NCSU, Spring Creating A Socket Parameters – domain: PF_INET – type: SOCK_DGRAM, SOCK_STREAM, SOCK_RAW – protocol: usually = 0 (i.e., default for type) Example #include … if ((s = socket(PF_INET, SOCK_STREAM, 0) < 0) perror("socket"); int s = socket(domain, type, protocol);
Copyright Rudra Dutta, NCSU, Spring After Creating A Socket (cont'd)
Copyright Rudra Dutta, NCSU, Spring Generic Address Structure Each protocol family defines its own address representation For each protocol family there is a corresponding address family – (e.g., PF_INET AF_INET, PF_UNIX AF_UNIX) Generalized address format: – struct sockaddr { u_charsa_len; /* total length */ u_short sa_family; /* type of address */ char sa_data[14]; /* value of address */ };
Copyright Rudra Dutta, NCSU, Spring Socket Addresses, Internet Style #include struct in_addr { u_long s_addr; /* 32-bit host address */ }; struct sockaddr_in { u_char sin_len; /* total length */ short sin_family; /* AF_INET */ u_short sin_port; /* network byte order */ struct in_addr sin_addr; /* network address */ char sin_zero[8]; /* unused */ };
Copyright Rudra Dutta, NCSU, Spring Binding the Local Address Used primarily by servers to specify their well-known port Optional for clients – normally, system chooses a “random” local port Use INADDR_ANY to allow the socket to receive datagrams sent to any of the machine's IP addresses int bind(int s, struct sockaddr *addr, int addrlen);
Copyright Rudra Dutta, NCSU, Spring Binding the Local Address (cont'd) … sin.sin_family = AF_INET; sin.sin_port = htons(6000); /* if 0:system chooses */ sin.sin_addr.s_addr = INADDR_ANY; /* allow any interface */ if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) /* error function here */
Copyright Rudra Dutta, NCSU, Spring After Binding the Local Address
Copyright Rudra Dutta, NCSU, Spring Establish a Connection Queue Only used for stream sockets Used by connection-oriented servers to place a socket in passive mode – makes it ready to accept incoming connections – the remote port # / IP address of the socket = 0 (any port, any IP address) Allows backlog pending connections to be waiting for accept() int listen(int s, int backlog);
Copyright Rudra Dutta, NCSU, Spring Accepting Connection Requests Executed by connection-oriented server, after listen() – blocks until a connection request from a client arrives Returns a new, unique socket ( newsock ) for data exchange with the client – this new socket is for the connection with port # / IP address of the client as the remote port and IP address – this new socket must be closed when the client and server are through communicating newsock = accept(int s, struct sockaddr *clientaddr, int *clientaddrlen);
Copyright Rudra Dutta, NCSU, Spring Accepting Connection Requests The original socket s (with 0 as remote address) remains open – when a TCP segment arrives for this host/port, and no existing socket has a remote IP address / port # = to the source IP address/port of the segment, the segment will be sent to the original socket s Must call accept() again to obtain the next connection request
Copyright Rudra Dutta, NCSU, Spring Accepting Connections (cont'd)
Copyright Rudra Dutta, NCSU, Spring Connecting To A Server Binds a permanent destination to a socket – uses 3-way handshake to establish connection (active open) As a side effect, it chooses a local endpoint (IP address and port number) if the socket does not have one – Cients normally let the system choose their (ephemeral) port # May fail – host not listening to port – timeout int connect(int s, struct sockaddr *servername, int servernamelen);
Copyright Rudra Dutta, NCSU, Spring Client-Server Interaction: TCP
Copyright Rudra Dutta, NCSU, Spring Sending and Receiving Data Types – read(), write() – recv(), send() – recvfrom(), sendto() Options: flags which modify action of a call – read() and write() may not specify options Notes – block size read may not = block size written – read from stream may read fewer bytes than requested
Copyright Rudra Dutta, NCSU, Spring Sending Data Flags control transmission – E.g., specify urgent data Write might not be able to write all buflen bytes (on a nonblocking socket) int write(int s, char* buf, int buflen); int send(int s, char* buf, int buflen, int flags);
Copyright Rudra Dutta, NCSU, Spring Receiving Data Flags control reception, e.g., – out-of-band data – message look-ahead Reminder! – block size read may not = block size written – read from stream may read fewer bytes than requested If the other end has closed the connection, and there is no buffered data, reading from a TCP socket returns 0 to indicate EOF int read(int s, char* buf, int buflen); int recv(int s, char* buf, int buflen, int flags);
Copyright Rudra Dutta, NCSU, Spring Closing A Connection Actions – decrements reference count for socket – terminates communication gracefully and removes socket when reference count = 0 Problem – server does not know if client has additional requests – client does not know if server has additional data to send int close(int s);
Copyright Rudra Dutta, NCSU, Spring Partially Closing A Connection Direction – 0 to close the input (reading) end – 1 to close the output (writing) end – 2 for both Used by client to specify it has no more data to send, without deallocating connection Server receives an EOF signal on read() or recv(), can then close connection after sending its last response int shutdown(int s, int direction);
Copyright Rudra Dutta, NCSU, Spring Datagram Communication First 4 arguments same as in send() Sends buflen bytes in buffer buf to location to, with options flags (usually 0) The return value of sendto() indicates how much data was accepted by the O.S. for sending as a datagram – not how much data made it to the destination – there is no error condition that indicates the destination did not get the data! int sendto(int s, char *buf, int buflen, int flags, struct sockaddr *to, int tolen);
Copyright Rudra Dutta, NCSU, Spring Datagram Communication (cont’d) First 4 arguments same as in recv() Receives up to len bytes into buffer buf – returns number of bytes received, 0 on EOF – if buf is not large enough, any extra data is lost forever recvfrom blocks until datagram available, by default Sets from to source address of data – sending replies is easy int recvfrom(int s, char *buf, int buflen, int flags, struct socaddr *from, int fromlen);
Copyright Rudra Dutta, NCSU, Spring Connected vs. Unconnected UDP Sockets UDP sockets can be connected or unconnected – in connected mode, client uses connect() to specify a remote endpoint – convenient to interact with a specific server repeatedly connect(): only records the remote address, does not initiate any packet exchange write(): sends a single message to the server read(): returns one complete message
Copyright Rudra Dutta, NCSU, Spring Closing UDP Sockets close() – releases the resources associated with a socket – does not inform the remote endpoint that the socket is closed shutdown() – can be used to mark socket as unwilling to transfer data in the direction specified – does not send any message to the other side
Copyright Rudra Dutta, NCSU, Spring Client-Server Interaction: UDP Contrast with TCP
Copyright Rudra Dutta, NCSU, Spring Byte Ordering Representation
Copyright Rudra Dutta, NCSU, Spring Byte-Order Transformations
Copyright Rudra Dutta, NCSU, Spring Byte-Order Transformations (cont’d) Byte ordering is a function of machine architecture – Intel: little-endian – Sparc, PowerPC: big-endian – Network order: big-endian Functions – u_long m = ntohl(u_long m) network-to-host byte order, 32 bit – u_long m = htonl(u_long m) host-to-network byte order, 32 bit – ntohs(), htons() short (16 bit) Be safe; it never hurts to use, and it improves portability
Copyright Rudra Dutta, NCSU, Spring Address Conversions Internally, IP addresses are represented as 32-bit integers int addr = inet_addr(char *str) addr : network byte order, str : dotted decimal form char *str = inet_ntoa(struct in_addr in)
Copyright Rudra Dutta, NCSU, Spring Obtaining Information About Hosts, etc. struct hostent *hptr; /* includes host address in binary */ hptr = gethostbyname(char *name); Ex.: gethostbyname(“ struct hostent *hptr; hptr = gethostbyaddr(char *addr, int addrlen, int addrtype); Ex.: gethostbyaddr(&addr, 4, AF_INET);
Copyright Rudra Dutta, NCSU, Spring Obtaining Information int inet_addr(char *dotdecimal); Ex.: sin_addr = inet_addr(“ ”); struct servent *sptr; /* includes port and protocol */ sptr = getservbyname(char *name, char *proto); Ex.: getservbyname(“smtp”, “tcp”); struct protoent *pptr; /* includes protocol number */ pptr = getprotobyname(char *name); Ex.: getprotobyname(“tcp”);
Copyright Rudra Dutta, NCSU, Spring Example of Connection Establishment // host - name of host to which connection is desired // service - service associated with the desired port // transport - name of transport protocol to use ("tcp“, "udp") memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; /* Map service name to port number */ if ( pse = getservbyname(service, transport) ) sin.sin_port = pse->s_port; else if ((sin.sin_port = htons((unsigned short)atoi(service))) == 0) errexit("can't get \"%s\" service entry\n", service);
Copyright Rudra Dutta, NCSU, Spring Example (cont’d) /* Map host name to IP address, allowing for dotted decimal */ if ( phe = gethostbyname(host) ) memcpy(&sin.sin_addr, phe->h_addr, phe->h_length); else if ((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE ) errexit("can't get \"%s\" host entry\n", host); /* Map transport protocol name to protocol number */ if ( (ppe = getprotobyname(transport)) == 0) errexit("can't get \"%s\" protocol entry\n", transport);
Copyright Rudra Dutta, NCSU, Spring Example (cont’d) /* Use protocol to choose a socket type */ if (strcmp(transport, "udp") == 0) type = SOCK_DGRAM; else type = SOCK_STREAM; /* Allocate a socket */ s = socket(PF_INET, type, ppe->p_proto); if (s < 0) errexit("can't create socket: %s\n", strerror(errno));
Copyright Rudra Dutta, NCSU, Spring Example (cont’d) /* Connect the socket */ if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) errexit("can't connect to %s.%s: %s\n", host, service, strerror(errno)); return s;