5

我有一个脚本应该能够对具有不同 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;

你知道是什么问题吗?!

提前感谢您的帮助!

4

2 回答 2

8

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

尝试:

use LWP::UserAgent 5.834; # need local_address

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

于 2012-03-02T23:24:39.913 回答
1

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

There's an un- (or at least under-) documented feature of LWP::Protocol::http that lets you set "extra socket options". I'm doing this in my code (using 5.824), and it works:

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

The same code in LWP/Protocol/http.pm seems to also exist in a much older LWP installed with perl 5.8 on an old RHEL4 system, so it's been around a while... :-)

于 2013-04-01T20:06:52.867 回答