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