的語法
利用 perl 的簡單語法來轉換 tw.txt 裡的 ip 樣式:
#編輯本檔為 32bit2ip.pl
$file = $ARGV[0];
sub toip {
$bit32 = @[0];
#$result = $bit32>>24,"." + $bit32<<8>>24,".",$bit32<<16>>24,".",$bit32<<24>>24;
$a = $bit32>>24;
$b = $bit32<<8>>24;
$c = $bit32<<16>>24;
$d = $bit32<<24>>24;
return "$a.$b.$c.$d";
}
open(F,"./$ARGV[0]");
while() {
chomp;
$ =~ s/"//g;
my($startIpNum,$endIpNum,$locId) = split(',',$_);
#print "$startIpNum\n";
$s = &toip($startIpNum);
$e = &toip($endIpNum);
print "$s-$e\n";
}
close F;
轉換後會得到IP
但是我一直轉換失敗
麻煩各位大大指點一下 拜託
我轉換後還是一堆數字 不是IP
你參考的那篇年代有點久,主要是現在都 64bit 的環境了,那篇用的是適用在 32bit 的作法。建議用系統提供的函式去處理,相容性會比較好,修正及化簡如下:
use Socket;
sub toip { &inet_ntoa(pack("N", $_[0])) }
while (<>) {
chomp;
my ($startIpNum, $endIpNum) = ($_ =~ m/\d+/g);
my $start_ip = &toip($startIpNum);
my $end_ip = &toip($endIpNum);
print "$start_ip-$end_ip\n";
}
至於執行的方法,就是 perl 32bit2ip.pl tw.txt
這個指令,若在 windows 可能是 perl.exe 32bit2ip.pl tw.txt
。
例如我在 linux 執行的結果是:
$ perl 32bit2ip.pl tw.txt
60.190.91.240-60.190.91.243
60.190.106.56-60.190.106.63
60.191.49.72-60.191.49.79
61.131.30.248-61.131.30.255
218.97.160.16-218.97.160.31
218.97.165.192-218.97.165.223
218.97.166.224-218.97.166.239
218.97.179.128-218.97.179.143
218.97.181.192-218.97.181.207
218.97.183.208-218.97.183.223
218.97.184.224-218.97.184.239
218.97.185.64-218.97.185.79