how do I find in C that a port is free to use?

后端 未结 3 1765
长情又很酷
长情又很酷 2021-02-14 02:19

The OS is Linux. I have a server process that can change its port realtime. However I would like to know in advance if a port is free before binding.

Scenario: Server bi

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 03:00

    If your server was told what port to use, just bind() it. Seriously.

    Sure, you could parse /proc/net/tcp and see if the port's in use. But then what? You still need to call bind() now that you know your port is free, and it'll tell you if the port was free then anyway, and so there was no point in groveling through /proc/net/tcp and doing all that (slow!) string production and parsing and extra kernel trips through not-very-well-optimized (read: super slow compared to bind()) diagnostic paths, just to get information that could well be out of date before you even finished parsing it. So just call bind() and be happy.

提交回复
热议问题