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 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<>
    require Exporter;
    use base 'Exporter';
    our @EXPORT = 'get_ip';
    our @EXPORT_OK = ();
sub get_ip {
    my $response = HTTP::Tiny->new->get('');
    die join(' ', 'Error fetching ip: ',
                  ($response->{status} or ''),
                  ($response->{reason} or '')) unless $response->{success};
    my $ip = $response->{content};
    chomp $ip;

It's a one file module, which simply contacts, 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!