### 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??

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"; } [download] 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|
|;

print "\t$_\n"; } [download] 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 192.168.0.1 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 >listaddrcsharp.exe 10.123.67.139 192.168.0.1 >perl d:\temp\in.pl 192.168.0.1 10.123.67.139 Perl code use Socket; use IO::Socket; my$machineName = lc($ENV{COMPUTERNAME}); my ($name, $aliases,$addrtype, $length, @addrs) = gethostbyname($mach
+ineName);
{
($a,$b,$c,$d)=unpack ('C4', $_); print "$a.$b.$c.\$d\n";
}
[download]
C# Code
 public static void Main(string[] args)
{

{
Console.WriteLine("    {0}", ip);
}
}
[download]

Don't use pack, use inet_ntoa or whatever (same low level as gethostbyname, now lower like pack), common mistake

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.

Create A New User
Node Status?
node history
Node Type: note [id://1039369]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2016-06-29 23:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My preferred method of making French fries (chips) is in a ...

Results (388 votes). Check out past polls.