Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Service: port to name

by carric (Beadle)
on Mar 21, 2004 at 18:02 UTC ( #338489=perlquestion: print w/replies, xml ) Need Help??
carric has asked for the wisdom of the Perl Monks concerning the following question:


I have been looking through the nodes for some mention of this, and I can't seem to find one.

I want to be able to translate a list of port numbers into their respective service names. e.g.:

tcp21: ftp
tcp22: ssh
tcp23: telnet
udp53: named

Anyone know how to do this? Thanks in advance!!


The function I was looking for appears to be getsrvbyport(), but the docs are a bit sparse.

Replies are listed 'Best First'.
Re: Service: port to name
by BazB (Priest) on Mar 21, 2004 at 18:20 UTC
    Net::IANA::PortNumbers or the standard Net::servent.

    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

      BTW, when you go to install this module, it is called Net::IANA::PortNumbers, BUT though the CPAN module, you have to call it New::IANA::PortNumber.

      %cpan>install Net::Install::PortNumber


      I think that might do it.

Re: Service: port to name
by chip (Curate) on Mar 21, 2004 at 22:42 UTC
    C'mon guys, give me a hard one. It's a core language feature: getservbyport().
    print scalar getservbyport(23,"tcp"),"\n" telnet

        -- Chip Salzenberg, Free-Floating Agent of Chaos

Re: Service: port to name
by jeffa (Bishop) on Mar 21, 2004 at 18:13 UTC

    If you don't mind building up a hash into memory every time you run it, and you don't mind not only having to hardcode the service, but also having to use the form '21/tcp' instead of '21tcp', then the following code should do the job:

    perl -lane'$h{$F[1]}=$F[0]}{print $h{"21/tcp"}' /etc/services
    But then again, it looks like i just reinvented a wheel called 'grep'. ;)

    I would be surprised if there is not an existing CPAN module for this task ... i don't know of one off hand ...


    (the triplet paradiddle with high-hat)
Re: Service: port to name
by pbeckingham (Parson) on Mar 21, 2004 at 18:07 UTC

    Try cat /etc/services.

Re: Service: port to name
by The Mad Hatter (Priest) on Mar 21, 2004 at 18:17 UTC
    Here's some code that generates a hash similar to Jeffa's, but it's not a one liner. Meant for use in another program...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://338489]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2016-10-27 00:27 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (350 votes). Check out past polls.