]> git.sur5r.net Git - openldap/blob - libraries/liblutil/sockpair.c
Added lutil_pair()
[openldap] / libraries / liblutil / sockpair.c
1 /*
2  * Copyright 1998-1999 The OpenLDAP Foundation, All Rights Reserved.
3  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
4  */
5
6 #include "portable.h"
7
8 #include <ac/socket.h>
9
10 /* Return a pair of descriptors that are connected to each other. The
11  * returned descriptors are suitable for use with select(). The two
12  * descriptors may or may not be identical; the function may return
13  * the same descriptor number in both slots. It is guaranteed that
14  * data written on fds[1] will be readable on fds[0]. The returned
15  * descriptors may be datagram oriented, so data should be written
16  * in reasonably small pieces and read all at once. On Unix systems
17  * this function is best implemented using a single pipe() call.
18  */
19 int lutil_pair( int fds[2] )
20 {
21         struct sockaddr_in si;
22         int rc, len = sizeof(si);
23         int fd;
24
25         fd = socket( AF_INET, SOCK_DGRAM, 0 );
26         if (fd < 0)
27                 return fd;
28         
29         (void) memset( (void*) &si, 0, len );
30         si.sin_family = AF_INET;
31         si.sin_port = 0;
32         si.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
33
34         if ( rc = bind( fd, (struct sockaddr *)&si, len ) )
35         {
36 fail:           tcp_close(fd);
37                 return rc;
38         }
39         if ( rc = getsockname( fd, (struct sockaddr *)&si, &len ) )
40                 goto fail;
41         if ( rc = connect( fd, (struct sockaddr *)&si, len ) )
42                 goto fail;
43         fds[0] = fds[1] = fd;
44         return 0;
45 }