in reply to Strawberry Perl: Windows hosts file not working?

I can vouch that gethostbyname will use the hosts file on Linux.

This one-liner resolves a hostname to an IPv4 address:

perl -w -MSocket -e 'my $pip=gethostbyname("www.google.com");my $ip=in +et_ntoa($pip);print $ip,"\n";'

"Normal" resolution via DNS returns: 142.250.72.132

If I add this line to /etc/hosts:
127.0.0.1 www.google.com

The above one-liner returns: 127.0.0.1

So on Linux, Perl will use the hosts file (Well, technically, it use the resolver library). However, I don't have a Windows machine with Perl handy to test with so I do not know if it will also work there. No good reason it shouldn't.

Replies are listed 'Best First'.
Re^2: Strawberry Perl: Windows hosts file not working?
by soonix (Chancellor) on Feb 14, 2022 at 07:47 UTC
    wouldn't that depend on what is defined in /etc/nsswitch.conf and/or /etc/host.conf? At least that's what man gethostbyname says.

      Yes, that is true. I haven't changed nsswitch.conf from the default for so long I'd forgotten about it.

      Mea Culpa

Re^2: Strawberry Perl: Windows hosts file not working?
by syphilis (Archbishop) on Feb 14, 2022 at 00:03 UTC
    However, I don't have a Windows machine with Perl handy to test with so I do not know if it will also work there.

    I couldn't get your example to work on Windows 7 with Strawberry Perl-5.32.0:
    C:\etc>type hosts 127.0.0.1 www.google.com.au C:\etc>perl -MSocket -wle "my $pip=gethostbyname('www.google.com.au'); +my $ip=inet_ntoa($pip);print $ip;" 142.250.66.195
    Maybe the hosts file needs to be elsewhere and/or named something else. (I also made a copy of etc/hosts named etc/hosts.txt.)

    Sorry ... I don't have much knowledge on this sort of stuff ... just reporting what I found.

    Cheers,
    Rob
      For such things I used C:\Windows\System32\drivers\etc\hosts in the past.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

        For such things I used C:\Windows\System32\drivers\etc\hosts in the past

        Aaah, yes - that looks right. (The file already exists.)
        Sorry for the noise.

        Cheers,
        Rob