]> git.sur5r.net Git - openldap/blob - libraries/liblutil/sockpair.c
5c33eb26d781c0bead2dadf64cad2b3564bd8f7a
[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         struct sockaddr_in si;
24         int rc, len = sizeof(si);
25         LBER_SOCKET_T sd;
26
27         sd = socket( AF_INET, SOCK_DGRAM, 0 );
28         if ( sd == AC_SOCKET_INVALID )
29                 return sd;
30         
31         (void) memset( (void*) &si, 0, len );
32         si.sin_family = AF_INET;
33         si.sin_port = 0;
34         si.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
35
36         rc = bind( sd, (struct sockaddr *)&si, len );
37         if ( rc == AC_SOCKET_ERROR ) {
38                 tcp_close(sd);
39                 return rc;
40         }
41
42         rc = getsockname( sd, (struct sockaddr *)&si, &len );
43         if ( rc == AC_SOCKET_ERROR ) {
44                 tcp_close(sd);
45                 return rc;
46         }
47
48         rc = connect( sd, (struct sockaddr *)&si, len );
49         if ( rc == AC_SOCKET_ERROR ) {
50                 tcp_close(sd);
51                 return rc;
52         }
53
54         sds[0] = sds[1] = sd;
55         return 0;
56 }