3

is it possible in any common platform - say, in Windows - to write a servient process that creates a socket, binds it to exactly one local "address:port" (fixed), and then:

  • use it to listen for incoming connections (on the specified port) while at the same time
  • use it as a client socket to connect to some other servient (having source port identical to the one it exposes to others) ?

that is (sorry for the syntax abuse):

mySocket=socket(); mySocket.bind(myaddress, 3000); mySocket.connectTo(neighbour, whateverport); // and present to others as port 3000 mySocket.listen(); // and it listens on 3000 mySocket.accept();

?

iirc, it's not even possible/advisable to try, even in the case an API wouldn't complain, but maybe it's me that is playing too much by the book... so I thought of asking you

thanks a lot!

user120747
  • 169
  • 1
  • 8
  • No, you'll need to create two sockets for that, but you can bind them to the same port as long as you set [SO_REUSEADDR/SO_REUSEPORT](https://stackoverflow.com/q/14388706/1048572) – Bergi Sep 17 '22 at 21:21

2 Answers2

2

No, a socket cannot be used for both listening and connecting at the same time. connect() will return a WSAEINVAL error if listen() was already called, and listen() will return a WSAEISCONN error if connect() was already called. You need to use separate sockets.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
2

And if you could, there's be all kinds of troubles that crop up. For example, if select() returns that the socket is readable, do you do a recv() or an accept()? You want 2 sockets to play those two roles.

What advantage is there in one socket? For example, if you were hoping to do a blocking read until something interesting happens (incoming connection, incoming data), there are alternatives. In that example, you'd use select() to block on two sockets at once. The result from select() tells you which socket is ready. That tells you if you want to accept() a new connection from the one socket or recv() new data from the other socket.

John M
  • 13,053
  • 3
  • 27
  • 26