2

I am trying to create a UDP server using perl IO::Socket::INET.

I am facing difficulty with using the following parameters:

  • LocalHost => "0.0.0.0"
  • LocalPort => 0

What I am trying to achieve is to:

  • Listen on all NICs, hence the use of 0.0.0.0
  • Have the OS pick a port, hence the use of 0 as the LocalPort

Using the parameters above with TCP, works just fine. When using those parameters for UDP, it doesn't work.

What I found to work with UDP, was specifying a LocalPort to something fixed and not specifying LocalHost at all, however this is not what I need.

The perl code I have is as follows:

my $sock = new IO::Socket::INET(
              LocalHost => "0.0.0.0",
              LocalPort => 0,
              Proto => 'udp') or die "failed $@";

What I use to assess if I achieved what I need or not is by checking the output of lsof -p <pid>. The following table summarizes what I am seeing in my trials:

Protocol LocalHost LocalPort sockport() output lsof -p output
TCP 0.0.0.0 0 48589 TCP *:48589 (LISTEN)
UDP 0.0.0.0 0 0 protocol: UDP
UDP Not specified 50001 50001 UDP *:50001
UDP output of hostname() 0 58066 UDP hostname:58066
UDP output of hostname() 50001 50001 UDP hostname:50001

The TCP trial in the first row's is what I am trying to achieve but for UDP and I am unable to.

Ayman Salah
  • 1,039
  • 14
  • 35
  • What is your rationale to use undefined/random port for UDP server? Are you intending to specify server UDP port for each client on it's start? How a client will know what port on the server it should connect to? Note: network ports 0-1024 require administrative/root privileges to be utilized. – Polar Bear Aug 17 '21 at 19:28
  • Why do you not want a port? Even if you can do that -- what I am not sure about -- How are clients going to know where to write? (Simply leaving port out runs without errors but I can't see any port on which this server is) – zdim Aug 17 '21 at 22:31
  • @PolarBear I call `sockport()` after the socket is created and a job is spawned on another machine with the port as a parameter and it sends stuff back. This script takes time to run and it should be possible to run it multiple times. Having a fixed port number will make it fail on the second run. – Ayman Salah Aug 18 '21 at 16:49
  • @zdim Not specifying a port is equivalent to passing 0 as the port number. This means that the OS will pick the port number for you. By calling `$sock->sockport()` after creating the socket will give you the port number that got opened. Also, inspecting the output of lsof -p of the perl process should give you the port number. – Ayman Salah Aug 18 '21 at 16:52

0 Answers0