Getting IP address with Perl

A common situation which you will usually come across, is to retrieve the IP.

Using WWW::curlmyip, this task is very easy.

use WWW::curlmyip;
my $ip = get_ip();

Lets inspect the module on https://metacpan.org/pod/WWW::curlmyip closely to understand how it works.

use strict;
package WWW::curlmyip;
$WWW::curlmyip::VERSION = '0.02';
use 5.008;
 
# ABSTRACT: Returns your ip address using L<http://curlmyip.com>
 
 
BEGIN {
    require Exporter;
    use base 'Exporter';
    our @EXPORT = 'get_ip';
    our @EXPORT_OK = ();
}
 
 
sub get_ip {
    my $response = HTTP::Tiny->new->get('http://curlmyip.com');
    die join(' ', 'Error fetching ip: ',
                  ($response->{status} or ''),
                  ($response->{reason} or '')) unless $response->{success};
    my $ip = $response->{content};
    chomp $ip;
    $ip;
}
 
1;
 
__END__
 


It's a one file module, which simply contacts http://curlmyip.com, retrieves the content with HTTP GET request, and finally chomps the result; because there exists an extra new line character which is useless.

So simple, isn't it ?
But It's also very useful !


Leave a comment

About Ashraf Bashir

user-pic Perling, Perling .... and Perling!