2011-04-19 92 views
1

我想獲取訪問者的ip地址記錄。我可以用PHP做到這一點,但是當我嘗試這個Perl代碼(Perl中的新手)時,當訪問者訪問我的網站時,它只記錄我網站的主機IP地址(在這種情況下爲三腳架),如下所示:19Apr11 20:25 :35 10.126.24.9。但那不是我想要的;我想要訪客的IP地址?我在這裏做錯了什麼?感謝Perl代碼獲取ip地址

#!/usr/bin/perl 
# For logging IP address of visitors. 
# This is stored into the cgi-bin folder and called from the index.htm file 
# using <img src="cgi-bin/script.pl"> 
# Specify location and name of log file to be maintained. 
my $LogFileLocation = "iplog.txt"; 
# Directory must exist and have correct permissions. 
use strict; 
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime; 
my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); 
$year += 1900; 
$year = substr($year,-2); 
$mday = $mday < 10 ? "0$mday" : $mday; 
$hour = $hour < 10 ? "0$hour" : $hour; 
$min = $min < 10 ? "0$min" : $min; 
$sec = $sec < 10 ? "0$sec" : $sec; 
my $address = $ENV{X_FORWARDED_FOR} || $ENV{REMOTE_ADDR} ||""; 
open W,">>$LogFileLocation"; 
print W "$mday$mon[$mon]$year $hour:$min:$sec\t$address\n"; 
close W; 
# end of script 
+5

所有這些日期代碼可以被簡化爲:'使用POSIX QW(strftime的);我的$ date = strftime('%d%b%y%H:%M:%S',localtime);' – toolic 2011-04-19 21:16:12

回答

5
use CGI; ## load the cgi module 

print "Content-type: text/plain; charset=iso-8859-1\n\n"; 
my $q = new CGI; ## create a CGI object 
print $q->remote_host(); ## print the user ip address 
+0

仍然沒有好處:1)與上面相同打印主機的地址,而不是訪客的地址,2)打印到日誌文件。 – francogrex 2011-04-19 20:57:57

+0

@francogrex:再試一次! remote_host()或$ ENV {REMOTE_ADDR}應該可以工作,他們爲我做,現在大約13年:) – 2011-04-19 21:27:57

+0

奇怪!不適合我。我仍然獲得本地主機IP(10.126.24.9)。也許這是主機以某種方式阻止某事。 – francogrex 2011-04-19 21:49:56