Unix errno Value
When an error occurs in a Unix function (such as one of the socket functions), the global variable errno is set to a positive value indicating the type of error and the function normally returns –1. Our err_sys function looks at the value of errno and prints the corresponding error message string (e.g., “Connection timed out” if errno equals ETIMEDOUT).
The value of errno is set by a function only if an error occurs. Its value is undefined if the function does not return an error. All of the positive error values are constants with all-uppercase names beginning with “E,” and are normally defined in the <sys/errno.h> header. No error has a value of 0.
A Simple Daytime Server
We can write a simple version of a TCP daytime server, which will work with the client.
#include "unp.h"
#include <time.h>
int main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
time_t ticks;
listenfd=Sock(AF_INET, SOCK_STREAM, 0);
bzeros(&servaddr, sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(13);
Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
for(;;)
{
connfd=Accept(listenfd, (SA *)NULL, NULL);
ticks=time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
Write(connfd, buff, strlen(buff));
Close(connfd);
}
}
Create a TCP socket
The style used throughout the book for an infinite loop is
for ( ; ; ) {
. . .
}
The current time and date are returned by the library function time, which returns the number of seconds since the Unix Epoch: 00:00:00 January 1, 1970, Coordinated Universal Time (UTC). The next library function, ctime, converts this integer value into a human-readable string such as
Mon May 26 20:58:40 2003
A carriage return and linefeed are appended to the string by snprintf, and the result is written to the client by write.