How do I reserve ports for my application?

How do I reserve a list of ports for my custom applications?

To be specific, the product I’m creating has a lot of processes and a lot of intercommunication between them.

The problem I’m having is that – every once in a while – the OS steals my ports. It’s rare, but it happens.

This could be because a different application has used “::bind” with no port specified.

Or sometimes my own applications steal the port when I call “::connect” with an unbound socket. As seen from the man page:

If the socket has not already been bound to a local address, connect() shall bind it to an address
which, unless the socket’s address family is AF_UNIX, is an unused local address.

So my question is, can I reserve the ports that I need so the OS doesn’t use them? Can this be accomplished with /etc/services? Or is there a different way?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

To ensure the kernel won’t give out 49000 and 49001 to clients as you wish to use them for your servers on linux.

sysctl -w net.ipv4.ip_local_reserved_ports = 49000, 49001

drop it in /etc/sysctl.conf, and then run sysctl -p.

Note that this is untested.

References

Method 2

Technically, there’s no such thing as a “reserved port”.

In TCP/UDP, the only way to “reserve” a port is to actually bind() a socket to it. A bound port will not be used by other applications; an unused port is, well, unused so other applications are free to use it.

If you are writing server software, then you can bind your sockets to specific ports as early as you want in the application code. Make the port numbers configurable, or at least clearly state them in the documentation, so that a systems administrator can quickly identify clashes and move conflicting applications to separate servers.

Method 3

Actually, the above answer is not entirely accurate. The sysctls net.inet.ip.portrange.first and net.inet.ip.portrange.last specify the range of ports the OS can allocate for random ports. You would want to make sure that the range of reserved ports for your application does not fall within these variables.

Take a look in the FreeBSD Handbook, section: 12.14. Tuning Kernel Limits.
But the same basic premise should apply to Linux as well.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x