Test for Socket Problems

steveh at hammer.UUCP steveh at hammer.UUCP
Wed Sep 5 05:07:28 AEST 1984


The following is sample program using Unix Domain sockets for
all those people who still can't figure out how to use them.

Some notes:
	o As distributed the include file /usr/include/sys/un.h
	  is wrong.  The max path length is 108 not 110 
	  (because it gets padded to 4 byte boundary).

	o The from address, returned from accept,
	  means nothing in Unix domain.

	o Casts to sockaddr are not strictly necessary, but keep lint
	  happy.

Here is the program:
-----
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCKET "/tmp/socktest"
struct sockaddr_un  sun = {
    AF_UNIX, SOCKET
};

main () {
    int     s, m;
    struct sockaddr from;
    int     fromlen = sizeof (from);

    unlink (SOCKET);

    if (fork () == 0) {
	sleep (10);
	if( (s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
	    perror ("child socket");
	if (connect (s, (struct sockaddr *) &sun, sizeof (sun)) < 0)
	    perror ("connect");
	printf ("child done\n");
    } else {
	if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
	    perror ("socket");
	if (bind (s, (struct sockaddr *) &sun, sizeof (sun)) < 0)
	    perror ("bind");
	if (listen (s, 1) < 0)
	    perror ("listen");
	m = 1 << s;
	if (select (20, &m, 0, 0, 0) < 0)
	    perror ("select");
	if (accept (s, &from, &fromlen) < 0)
	    perror ("accept");
	printf ("parent done\n");
	close(s);
	unlink(SOCKET);
    }
    exit (0);
}



More information about the Comp.unix.wizards mailing list