]> git.sur5r.net Git - openldap/blob - libraries/liblutil/sockpair.c
happy new year
[openldap] / libraries / liblutil / sockpair.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2007 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15
16 #include "portable.h"
17 #include <ac/socket.h>
18 #include <ac/unistd.h>
19
20 #include <lutil.h>
21
22 /* Return a pair of socket descriptors that are connected to each other.
23  * The returned descriptors are suitable for use with select(). The two
24  * descriptors may or may not be identical; the function may return
25  * the same descriptor number in both slots. It is guaranteed that
26  * data written on sds[1] will be readable on sds[0]. The returned
27  * descriptors may be datagram oriented, so data should be written
28  * in reasonably small pieces and read all at once. On Unix systems
29  * this function is best implemented using a single pipe() call.
30  */
31
32 int lutil_pair( ber_socket_t sds[2] )
33 {
34 #ifdef USE_PIPE
35         return pipe( sds );
36 #else
37         struct sockaddr_in si;
38         int rc, len = sizeof(si);
39         ber_socket_t sd;
40
41         sd = socket( AF_INET, SOCK_DGRAM, 0 );
42         if ( sd == AC_SOCKET_INVALID ) {
43                 return sd;
44         }
45         
46         (void) memset( (void*) &si, '\0', len );
47         si.sin_family = AF_INET;
48         si.sin_port = 0;
49         si.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
50
51         rc = bind( sd, (struct sockaddr *)&si, len );
52         if ( rc == AC_SOCKET_ERROR ) {
53                 tcp_close(sd);
54                 return rc;
55         }
56
57         rc = getsockname( sd, (struct sockaddr *)&si, &len );
58         if ( rc == AC_SOCKET_ERROR ) {
59                 tcp_close(sd);
60                 return rc;
61         }
62
63         rc = connect( sd, (struct sockaddr *)&si, len );
64         if ( rc == AC_SOCKET_ERROR ) {
65                 tcp_close(sd);
66                 return rc;
67         }
68
69         sds[0] = sd;
70 #if !HAVE_WINSOCK
71         sds[1] = dup( sds[0] );
72 #else
73         sds[1] = sds[0];
74 #endif
75         return 0;
76 #endif
77 }