TCP Server w/o listening/accept???

I havew a need to grant a TCP socket connection from a remote process. But I only want to allow one connection, and I don't want to have to use the accept function.

In other words, after I create and bind the socket, I'd like to listen for a connection on the existing file descriptor that is created when you create the TCP server socket.

Of course, life is full of wants, so I'm not going to jump off of a bridge if it can't be done.... however, I figure if it can be done, someone on this forum knows how.

VR/JW
Something along these lines, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>

int connected_socket( int domain, const ::sockaddr* addr, socklen_t length )
{
    int socket_fd = -1 ;

    int listen_fd = ::socket( domain, SOCK_STREAM, 0 ) ;

    if( listen_fd != -1 )
    {
        if( ::bind( listen_fd, addr, length ) != -1 && ::listen( listen_fd, 1 ) != -1 )
            socket_fd = ::accept( listen_fd, nullptr, 0 ) ; // accept the first connection

        ::close(listen_fd) ; // close the listening socket, only the first connection is accepted
    }

    return socket_fd ;
}
Last edited on
JL Borges... What a sweet and elegant solution!!!!
All of these years programming and I didn't see that.
Thank you so much!!!!
Topic archived. No new replies allowed.