Search code examples
perlport-number

TCP port keeps changing with perl LWP in loop


I'm analyzing a small LWP useragent in a loop with an HTTP analyzer and I noticed that every visit of the URL my port keeps changing.

While I have a small script also made in VB.Net httpwebrequest and that isn't changing my port number while visiting the URL 10 times.

Is it possible to keep a static ip:port while using perl?


Solution

  • For the HTTP client:

    use LWP::Protocol::http qw( );
    
    @LWP::Protocol::http::EXTRA_SOCK_OPTS = (
        LocalPort => $port,
    );
    

    If you also want to use a specific interface,

    @LWP::Protocol::http::EXTRA_SOCK_OPTS = (
        LocalAddr => $ip,
        LocalPort => $port,
    );
    

    Of course, you run into problems if the port is already in use, which is likely if you just used it for another connection.

    use LWP::Protocol::http qw( );
    use LWP::UserAgent      qw( );
    
    my $port = 12456;
    @LWP::Protocol::http::EXTRA_SOCK_OPTS = (
        LocalPort => 12456,
    );
    
    my $ua = LWP::UserAgent->new();
    print $ua->get('http://www.example.com/show_port')->content for 1..2;
    

    Output:

    >script.pl
    12456
    Can't connect to www.example.com:80 (10048)
    
    LWP::Protocol::http::Socket: connect: 10048 at .../LWP/Protocol/http.pm line 51.
    
    >perl -E"say $^E=10048"
    Only one usage of each socket address (protocol/network address/port) is normally permitted
    

    More likely, the port is not being reused, the connection is. You could also try reusing the connection by passing keep_alive => 1 to the LWP::UserAgent constructor.

    use LWP::UserAgent qw( );
    
    my $ua = LWP::UserAgent->new( keep_alive => 1 );
    print $ua->get('http://www.example.com/show_port')->content for 1..2;
    

    Output:

    57842
    57842