Skip to content Skip to sidebar Skip to footer

Can I Use The Same Socket For Multiple Connections?

I'm trying to make a python function that scans a range of addresses. I started a socket and pass the socket as an argument to the function that connects to it: def scan(socket, ad

Solution 1:

Do I need to start a new socket for each connection?

Yes.

I'm trying to read about socket reusage

There is no such thing as 'socket reusage'. There is port reuse. Not the same thing. You cannot reconnect an existing socket once you've tried to connect it, even if the connect attempt failed.

I found that there exists flags like SO_ADDREUSE or something like that

SO_REUSEADDR means to reuse the port. Not the socket.

Solution 2:

I'm trying to think how a socket works. I think the moment I create one, it choses a tcp source port,

Between creating a socket using the socket() system call and using it to create an outgoing connection with the connect() system call, there is an opportunity to optionally use the bind() system call to set source IP address and/or port if you want to. If you don't use bind(), the operating system will automatically bind the socket to the first available port in the appropriate range when you use the connect() system call. In this case, the source IP address is normally selected to match the network interface that provides the shortest route to the specified destination according to the routing table.

At least, that's how it works at the system call level. Some programming languages or libraries may choose to combine some of these operations into one.

To your actual question, man 7 ip says:

A TCP local socket address that has been bound is unavailable for some time after closing, unless the SO_REUSEADDR flag has been set. Care should be taken when using this flag as it makes TCP less reliable.

The idea is to delay the re-use of a port until any possible re-sent copies of packages that belonged to the closed connection have for sure expired on the network.

According to the bind() man page, trying to re-bind a socket that is already bound to an address will result in an EINVAL error. So "recycling" a socket using bind(socket, INADDR_ANY, 0) (after ending a connection that used SO_REUSEADDR) does not seem to be possible.

And even if that would be possible, when you're using multiple threads on a modern multi-core system, you end up (very probably) doing multiple things in parallel. A socket can be used for just one outgoing connection at a time. Each of your scan threads will need its own socket.

Post a Comment for "Can I Use The Same Socket For Multiple Connections?"