BSD Sockets Interface Programmer's Guide
Chapter 7 161
Using UNIX Domain Datagram Sockets
Example Using UNIX Domain Datagram Sockets
alarm((unsigned long) 120);
/* Create a UNIX datagram socket for server */
if ((sock = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) {
perror(”server: socket”);
exit(1);
}
/* Set up address structure for server socket */
bzero(&servaddr, sizeof(servaddr));
servaddr.sun_family = AF_UNIX;
strcpy(servaddr.sun_path, SOCKET_PATH);
if (bind(sock, &servaddr, sizeof(servaddr)) < 0) {
close(sock);
perror(”server: bind”);
exit(2);
}
/* Receive data from anyone, echo back data to the sender
* Note that fromlen is passed as pointer so recvfrom
* call can return the size of the returned address.
*/
expect = 5 * 2000;
while (expect > 0) {
fromlen = sizeof(from);
rlen = recvfrom(sock, sdata, 2000, 0, &from, &fromlen);
if (rlen == -1) {
perror(”server : recv\n”);
exit(3);
} else {
expect -= rlen;
printf(”server : recv'd %d bytes\n”,rlen);
slen = sendto(sock, sdata, rlen, 0, &from,
fromlen);
if (slen <0) {
perror (”server : sendto\n”);
exit (4);
}
}
}
/* Use unlink to remove the file (inode) so that the
* name will be available for the next run.
*/
unlink(SOCKET_PATH);
close(sock);
printf(”Server done\n”);
exit(0);
}
timeout() /* escape hatch so blocking calls don't wait forever */
{
printf( “alarm received — stopping server\n” );
fprintf(stderr, “stopping the server process\n”);
exit(5);
}
/*
* AF_UNIX datagram client process
*
* This is an example program that demonstrates the use of
* AF_UNIX datagram sockets as a BSD Sockets mechanism. This
* contains the client, and is intended to operate in
* conjunction with the server program.