]> git.sur5r.net Git - openldap/blob - libraries/liblutil/sockpair.c
f45bdd753c6657b4dce0f629ac8ccf51784bc3e4
[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 < 0)
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         if ( rc = bind( sd, (struct sockaddr *)&si, len ) ) {
37                 tcp_close(sd);
38                 return rc;
39         }
40
41         if ( rc = getsockname( sd, (struct sockaddr *)&si, &len ) ) {
42                 tcp_close(sd);
43                 return rc;
44         }
45
46         if ( rc = connect( sd, (struct sockaddr *)&si, len ) ) {
47                 tcp_close(sd);
48                 return rc;
49         }
50
51         sds[0] = sds[1] = sd;
52         return 0;
53 }