Skip to content

Commit

Permalink
added ipv6 support
Browse files Browse the repository at this point in the history
  • Loading branch information
abu-usama committed Jan 8, 2024
1 parent 735e47c commit 28e3291
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 8 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
./t
.vscode
22 changes: 16 additions & 6 deletions Geo-IPinfo/lib/Geo/IPinfo.pm
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ my %valid_fields = (
domains => 1,
);
my $base_url = 'https://ipinfo.io/';
my $base_url_ipv6 = 'https://v6.ipinfo.io/';
my $country_flag_url = 'https://cdn.ipinfo.io/static/images/countries-flags/';
my $cache_ttl = 0;
my $custom_cache = 0;
Expand Down Expand Up @@ -1060,8 +1061,9 @@ sub new {
my $self = {};
$token = defined $token ? $token : '';

$self->{base_url} = $base_url;
$self->{ua} = LWP::UserAgent->new;
$self->{base_url} = $base_url;
$self->{base_url_ipv6} = $base_url_ipv6;
$self->{ua} = LWP::UserAgent->new;
$self->{ua}->ssl_opts( 'verify_hostname' => 0 );
$self->{ua}->default_headers(
HTTP::Headers->new(
Expand Down Expand Up @@ -1198,7 +1200,9 @@ sub _lookup_info {
return ( $cached_info, '' );
}

my ( $source_info, $message ) = $self->_lookup_info_from_source($key);
my $is_ipv6 = 0;
$is_ipv6 = 1 if ( $ip =~ /:/ );
my ( $source_info, $message ) = $self->_lookup_info_from_source($is_ipv6, $key);
if ( not defined $source_info ) {
return ( $source_info, $message );
}
Expand Down Expand Up @@ -1253,9 +1257,15 @@ sub _lookup_info_from_cache {
}

sub _lookup_info_from_source {
my ( $self, $key ) = @_;

my $url = $self->{base_url} . $key;
my ( $self, $is_ipv6, $key ) = @_;

my $url = '';
if ( $is_ipv6 ) {
$url = $self->{base_url_ipv6} . $key;
} else {
$url = $self->{base_url} . $key;
}

my $response = $self->{ua}->get($url);

if ( $response->is_success ) {
Expand Down
16 changes: 14 additions & 2 deletions example.pl
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,20 @@
print $ipinfo->error_msg . "\n";
}

# you can also retrieve information for IPv6 addresses in a similar fasion
my $ipv6_data = $ipinfo->info('2001:4860:4860::8888');
if ( defined $ipv6_data ) # valid data returned
{
# print JSON string
my $json = JSON->new->allow_blessed->convert_blessed;
my $json_string = $json->utf8->pretty->encode($ipv6_data);
print $json_string . "\n";
}
else # invalid data obtained, show error message
{
print $ipinfo->error_msg . "\n";
}

# retrieve only city information of the IP address
my $details = $ipinfo->field( '8.8.8.8', 'city' );

print "The city of 8.8.8.8 is " . $details->city . "\n";

0 comments on commit 28e3291

Please sign in to comment.