简体   繁体   中英

Why I can't assign an ip to LWP::UserAgent?

I have a script that should be able to do some calls to a service with different IP addresses. My code works when I don't set any ip to my calls, I wrote a function to assign an IP to the object before doing calls, but it returns an error:

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

This is my functions structure:

#!/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();
}

And this is the way that I call them:

set_caller_ip($caller_ip_address);

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

Do you know what's the issue?!

Thanks for your help in advance!

The local_address attribute was added in LWP::UserAgent version 5.834. Could you be using an older version?

Try:

use LWP::UserAgent 5.834; # need local_address

(Whenever I specify a minimum version for a module, I try to add a brief comment explaining why that's the minimum version.)

@cjm has already answered the question about your error, but it might be useful to note an alternative for older versions of 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... :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM