Sven Van Caekenberghe wrote
> 
> You can try, maybe it solves your 'problem'.
> 

Thanks, Sven!

It works, but not for ip6. I guess this is more complicated than I thought.
OS X lets me listen on a port that's already listening with ip6.

before I open my port, lsof shows:
java      ...  IPv6 ...  TCP *:port_number (LISTEN)

and after:
java      ...  IPv6 ...  TCP *:port_number (LISTEN)
CogVM  ...  IPv4 ...  TCP *:same_port_number!!! (LISTEN)

WTF!

For now, I'm using the ugly and non-portable:
        | lsof output p portsInUse |
        lsof := PipeableOSProcess waitForCommand: 'lsof -i -P -FnT'.
        output := p output.
        portsInUse := Set new.
        "Output is e.g. 'n*:52844TST=LISTENTQR=0TQS=0', where there is an lf
between each field i.e. between the 4 at the end of the example's port
number and the T, which starts the status info, and the next address"
        "So we're matching the colon before the port number, the number, lf (now
we're in the status info), and then LISTEN before the next lf (when the next
address begins)"
        output regex: '\:[[:digit:]]+\s\S*LISTEN' matchesDo: [ :e | portsInUse 
add:
e allButFirst asNumber ].
        isAvailable := (portsInUse includes: my_port) not.

but it seems like it'd be nice to have a portable way, since it's generally
useful, e.g. in zinc's tests, if I open port 1700 and run the server tests,
they fail intermittently. With an appropriate comment to the ip6 limitation,
I think this would be very useful:

  "Would this go in ZnNetworkingUtils? ZnUtils?"
  isPortAvailable: aNumber
        "Does not take ip6 into account i.e. if the port is already open with 
ip6,
will indicate it is available"

        | socket isAvailable |
        socket := Socket newTCP listenOn: aNumber.
        isAvailable := socket isValid and: [ socket localPort = aNumber ].
        socket destroy.
        ^ isAvailable.

then the server tests could be more robust...
  ZnServerTests>>port
        ^ (1700 to: 1750) detect: [ :e | ZnNetworkingUtils isPortAvailable: e ].

and here's a test for the new functionality...
    testIsPortAvailable

        | availablePort utils socket |
        utils := ZnNetworkingUtils default.
        availablePort := (1700 to: 1800) detect: [ :e | utils isPortAvailable: 
e ].
        
        socket := Socket newTCP listenOn: availablePort.
        self deny: (utils isPortAvailable: availablePort).

        socket destroy.
        self assert: (utils isPortAvailable: availablePort).

--
View this message in context: 
http://forum.world.st/Listening-on-sockets-tp4618129p4618367.html
Sent from the Pharo Smalltalk Users mailing list archive at Nabble.com.

Reply via email to