Actually, your code works fine for me. Here's what I suspect is happening: it's taking a long time to run, so you hit control-C or something similar to interrupt. When you do, you discover that the file is empty! I had the same problem. By setting the ranges to smaller values, I was able to let the program finish running. Then, the file was written out just fine!
Perl is buffering the filehandle. Data does not get written to the file until the buffer is full. What you need to do is either wait for the buffer to be full and the data to be written or unbuffer the handle. I rewrote the snippet and fixed your problem. This could still be improved, but it's a bit cleaner:
#!/usr/bin/perl -w use strict; use Socket; my $logfile = 'hosts.txt'; open HOST, ">> $logfile" or die "Can't open $logfile: $!\n"; # The following snippet will unbuffer your filehandle # so that data is written out immediately. { my $ofh = select HOST; $| = 1; select $ofh; } for my $i ( 0 .. 255 ) { for my $j ( 0 .. 255 ) { for my $k ( 0 .. 255 ) { for my $l ( 0 .. 255 ) { my $address = "$i.$j.$k.$l"; my $iaddr = inet_aton( $address ); my $name = gethostbyaddr($iaddr, AF_INET) || ''; chomp $name if $name; print "$address\t$name\n"; print HOST "$address\t$name\n" or die "Can't print to +$logfile: $!"; } } } } close HOST or die "Can't close $logfile: $!";
By the way, if you want to understand what is actually causing the problem, read this.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to (Ovid - not printing) Re: gethostbyaddr
by Ovid
in thread gethostbyaddr question
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |