为什么我不能将ip分配给LWP :: UserAgent?

时间:2012-03-02 23:11:23

标签: perl ip lwp-useragent

我有一个脚本应该能够对具有不同IP地址的服务进行一些调用。当我没有为我的调用设置任何ip时,我的代码工作,我写了一个函数来在调用之前为对象分配IP,但是它返回一个错误:

Can't locate object method "local_address" via package "LWP::UserAgent"

这是我的功能结构:

#!/usr/bin/perl -w

use LWP::UserAgent;
use HTTP::Headers;
use HTTP::Request::Common;
use HTTP::Cookies;
use URI::Escape;
use HTML::LinkExtor;

# set user agent object values
my $ua = new LWP::UserAgent;
$ua->agent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6');
push @{ $ua->requests_redirectable }, 'POST';
$ua->cookie_jar({});


sub set_caller_ip {
    my($set_ip_address) = @_;

    $ua->local_address("$set_ip_address");
    return 1;
}


sub test_caller_ip {

    my $req = new HTTP::Request('GET', 'http://whatismyip.org/');
    $req->headers->push_header('Connection','Keep-Alive');
    $req->headers->push_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
    my $res = $ua->request($req) or die "$!";

    return $res->content();
}

这就是我称之为的方式:

set_caller_ip($caller_ip_address);

$caller_ip_tested = test_caller_ip();
print "\$caller_ip_tested=".$caller_ip_tested."\n";die;

你知道这是什么问题吗?!

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:8)

LWP::UserAgent版本5.834中添加了local_address属性。你可以使用旧版本吗?

尝试:

use LWP::UserAgent 5.834; # need local_address

(每当我指定模块的最低版本时,我会尝试添加简短的注释来解释为什么这是最低版本。)

答案 1 :(得分:1)

@cjm已经回答了有关您的错误的问题,但是注意旧版本的LWP :: UserAgent的替代方案可能会有用。

LWP :: Protocol :: http有一个非(或至少未完成)记录的功能,可让您设置"额外的套接字选项"。我在我的代码中执行此操作(使用5.824),它可以工作:

@LWP::Protocol::http::EXTRA_SOCK_OPTS = { LocalAddr => "10.11.12.13" };

LWP / Protocol / http.pm中的相同代码似乎也存在于旧RHEL4系统上使用perl 5.8安装的更旧的LWP中,所以它已经有一段时间......: - )< / p>