Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: gethostbyname returns reverse order of ipaddress expected

by Khen1950fx (Canon)
on Jun 17, 2013 at 13:47 UTC ( #1039369=note: print w/replies, xml ) Need Help??

in reply to gethostbyname returns reverse order of ipaddress expected

gethostbyname works for me. You didn't provide your code, so I can't tell if you are using it in the right way. I would do something like this:
#!/usr/bin/perl use strict; use warnings; use Socket; my $packed_ip = gethostbyname('localhost.localdomain'); if (defined $packed_ip) { my $ip_address = inet_ntoa($packed_ip); print $ip_address, "\n"; }
Make sure that you check for definedness.

Using Sys::Hostname::FQDN, you can do an ascii-version of Anonymous Monk's post like this:

#!/usr/bin/perl BEGIN { $| = 1; $^W = 1; } use strict; use warnings; use Socket; use Sys::Hostname::FQDN qw( asciihostinfo gethostinfo fqdn short ); my($name,$aliases,$addrtype,$length,@addrs) = asciihostinfo(); print qq|host info short name : |, short(), qq| long name ; |, fqdn(), qq| aliases : |, $aliases, qq| address type : |, $addrtype, qq| address length: |, $length, qq| IP address(es): |; foreach(@addrs) { print "\t$_\n"; }

Replies are listed 'Best First'.
Re^2: gethostbyname returns reverse order of ipaddress expected
by anubhavd (Initiate) on Jun 17, 2013 at 22:35 UTC
    I should have been clearer its the choice of ipaddress to return that's the issue. If I return all addresses it get it in a reverse order than a C# program (both are copied below). if I use Khen1950fx's first example I get the answer as which is the wrong address to use. Code that picks the first address to use now breaks down on a multiadapter machines.

    Outputs via C# and perl


    >perl d:\temp\

    Perl code
    use Socket; use IO::Socket; my $machineName = lc($ENV{COMPUTERNAME}); my ($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($mach +ineName); foreach(@addrs) { ($a,$b,$c,$d)=unpack ('C4', $_); print "$a.$b.$c.$d\n"; }
    C# Code
    public static void Main(string[] args) { IPAddress[] ips; ips = Dns.GetHostAddresses(Environment.MachineName); foreach (IPAddress ip in ips) { if (ip.AddressFamily == AddressFamily.InterNetwork) Console.WriteLine(" {0}", ip); } }
        As I described in the 2 outputs, the C# one returns addresses in the correct order (increasing interface metric) while the perl one returns it in the reverse order (decreasing metric). It has nothing to do with the byte order of the individual ip address.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1039369]
and snow settles gently...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2017-06-28 16:43 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (641 votes). Check out past polls.