Examples 14-1 and 14-2 are small server and client programs that transfer data between themselves using a virtual circuit. These two programs are identical in operation to the programs in Examples 13-6 and 13-7, except they are implemented using Internet-domain sockets.
Example 14-1: server
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define PORTNUMBER 12345
int
main(void)
{
char buf[1024];
int n, s, ns, len;
struct sockaddr_in name;
/*
* Create the socket.
*/
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
/*
* Create the address of the server.
*/
memset(&name, 0, sizeof(struct sockaddr_in));
name.sin_family = AF_INET;
name.sin_port = htons(PORTNUMBER);
len = sizeof(struct sockaddr_in);
/*
* Use the wildcard address.
*/
n = INADDR_ANY;
memcpy(&name.sin_addr, &n, sizeof(long));
/*
* Bind the socket to the address.
*/
if (bind(s, (struct sockaddr *) &name, len) < 0) {
if (connect(s, (struct sockaddr *) &name, len) < 0) {
perror("connect");
exit(1);
}
/*
* Read from standard input, and copy the
* data to the socket.
*/
while ((n = read(0, buf, sizeof(buf))) > 0) {
if (send(s, buf, n, 0) < 0) {
perror("send");
exit(1);
}
}
close(s);
exit(0);
}
% server &
% client < /etc/motd
Sun Microsystems Inc. SunOS 5.3 Generic September 1993
Example 14-3 shows a sample datagram client program that contacts the “daytime” service on every host named on the command line. The “daytime” service is an Internet standard service that returns the local time (to the server) in an ASCII string. It is defined for both TCP and UDP; try modifying the program to use TCP instead.