DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Interprocess communication using UNIX domain sockets

Datagrams in the UNIX domain

Unlike the previous examples, which dealt with streams sockets, the following two sample programs send and receive data on datagram sockets. These examples are for the UNIX domain; for the Internet domain equivalents, see ``Datagrams in the Internet Domain''.

First, create a server that can receive UNIX domain datagrams:

Reading UNIX domain datagrams

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

/* * In the included file <sys/un.h> a sockaddr_un is defined as follows * struct sockaddr_un { * short sun_family; * char sun_path[108]; * }; */

#include <stdio.h>

#define NAME "socket"

/* * This program creates a UNIX domain datagram socket, binds a name to it, * then reads from the socket. */ main() { int sock, length; struct sockaddr_un name; char buf[1024];

/* Create socket from which to read. */ sock = socket(AF_UNIX, SOCK_DGRAM, 0); if (sock < 0) { perror("opening datagram socket"); exit(1); }

/* Create name. */ name.sun_family = AF_UNIX; strcpy(name.sun_path, NAME);

/* Bind the UNIX domain address to the created socket */ if (bind(sock, (struct sockaddr *) &name, sizeof(struct sockaddr_un))) { perror("binding name to datagram socket"); exit(1); } printf("socket -->%s\n", NAME);

/* Read from the socket */ if (read(sock, buf, 1024) < 0) perror("receiving datagram packet"); printf("-->%s\n", buf); close(sock); unlink(NAME); }

The following sample code creates a client and sends datagrams to a server like the one created in the previous example. For the Internet domain equivalent example, see `` Sending an Internet domain datagram''.

Sending UNIX domain datagrams

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>

#define DATA "The sea is calm tonight, the tide is full . . ."

/* * Send a datagram to a receiver whose name is specified in the command * line arguments. The form of the command line is <programname> <pathname> */

main(argc, argv) int argc; char *argv[]; { int sock; struct sockaddr_un name;

/* Create socket on which to send. */ sock = socket(AF_UNIX, SOCK_DGRAM, 0); if (sock < 0) { perror("opening datagram socket"); exit(1); } /* Construct name of socket to send to. */ name.sun_family = AF_UNIX; strcpy(name.sun_path, argv[1]); /* Send message. */ if (sendto(sock, DATA, sizeof(DATA), 0, &name, sizeof(struct sockaddr_un)) < 0) { perror("sending datagram message"); } close(sock); }


Next topic: Socketpair sample code (UNIX only)
Previous topic: Sample UNIX client

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003