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