Looking for a free network port to listen on

In a server, I would like to suggest a free port number to listen on after I invite a client to connect to.
I'm thinking of using high-numbered ports (maybe above 50000 or 60000 .. aren't there a bunch of ports there that aren't already dedicated to particular services?) But is there a way to ask if a port is currently in use (i.e., already being listened to by some or other service?
Why do I need this? because the server may behind a dynamic address translation firewall, and one of the ways these are often configured is to change the remote IP addresses on oncoming messages to the local IP address of the router. So each connection from outside the LAN will need its own IP port number if it is to be a persistent connection. (might be in use continuously for an hour or longer.)

It sounds like you want "ephemeral" ports? Give 0 as the port argument to tcp-listen and it will pick a free one.

p.s.

Although I'm a little rusty on this topic:

I think NATs will keep the connection alive indefinitely if you send some traffic frequently enough; a little keep-alive message to keep your addresses in their MRU cache. Having said that, sometimes you'll get flushed and must reconnect.


p.p.s. Some NATs will prevent your server from accepting connections in the first place. They accept traffic from only from an address to which they've already sent traffic (recently enough).

To work in more cases, you'll need some server outside any NAT, at least to help make the connection. Like with peer-to-peer, you need a 3rd server to help make the connection using ICE and STUN; thereafter the the peers can talk directly "indefinitely".

1 Like

Yes, that looks like exactly what I want. Thank you!

-- hendrik

p.s.

[quote="hendrikboom3, post:1, topic:2446"]
Why do I need this? because the server may behind a dynamic address translation firewall, and one of the ways these are often configured is to change the remote IP addresses on oncoming messages to the local IP address of the router. So each connection from outside the LAN will need its own IP port number if it is to be a persistent connection. (might be in use continuously for an hour or longer.)

The VDSL moem provided by my ISP has NAT built in, but it is quite configurable. In particular, I can tell it which ports are to be sent to which machines behind the firewall, and I've instruted it to send all unspecified ports to one particular machine, which is almost always on (except for power outages) and hosts my web site, http://topoi.pooq.co/hendrik . (No 's' on http:)

so there's a chance I gan get this to work.

I will of course continue to investigate possibilities.

-- hendrik