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