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;
use
warnings;
package
WWW::curlmyip;
$WWW::curlmyip::VERSION
=
'0.02'
;
use
HTTP::Tiny;
use
5.008;
# ABSTRACT: Returns your ip address using L<http://curlmyip.com>
BEGIN {
our
@EXPORT
=
'get_ip'
;
our
@EXPORT_OK
= ();
}
sub
get_ip {
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