]> git.sur5r.net Git - openldap/blob - libraries/liblutil/sockpair.c
Forced commit, undo previous accidental checkin.
[openldap] / libraries / liblutil / sockpair.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2002 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( ber_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         ber_socket_t sd;
31
32         sd = socket( AF_INET, SOCK_DGRAM, 0 );
33         if ( sd == AC_SOCKET_INVALID ) {
34                 return sd;
35         }
36         
37         (void) memset( (void*) &si, '\0', len );
38         si.sin_family = AF_INET;
39         si.sin_port = 0;
40         si.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
41
42         rc = bind( sd, (struct sockaddr *)&si, len );
43         if ( rc == AC_SOCKET_ERROR ) {
44                 tcp_close(sd);
45                 return rc;
46         }
47
48         rc = getsockname( sd, (struct sockaddr *)&si, &len );
49         if ( rc == AC_SOCKET_ERROR ) {
50                 tcp_close(sd);
51                 return rc;
52         }
53
54         rc = connect( sd, (struct sockaddr *)&si, len );
55         if ( rc == AC_SOCKET_ERROR ) {
56                 tcp_close(sd);
57                 return rc;
58         }
59
60         sds[0] = sd;
61 #if !HAVE_WINSOCK
62         sds[1] = dup( sds[0] );
63 #else
64         sds[1] = sds[0];
65 #endif
66         return 0;
67 #endif
68 }