Checking open ports in C / C ++

There were other questions regarding the topic of checking the availability and accessibility of socket ports.

How can I search for a port for dynamic listening in C / C ++?

The main process that I am trying to perform is as follows:

  • Client launches
  • The client finds the open XYZ port and listens for it.
  • The client sends the basic message "I am here" through UDP datagrams to the server with port information
  • The client and server can communicate.

I know you can do something like this if you select an arbitrary port number and try bind . If this fails, increase the number and try again until you get a successful binding.

Is there a more elegant way to do this? These seem to be hacks.

+3
source share
1 answer

If you are bound to port 0, a random port will be assigned. Getsockname () can then be used to determine the actual port used.

+12
source

Source: https://habr.com/ru/post/1750366/


All Articles