Home > Blockchain >  Bash - increment IPv6 address by 1
Bash - increment IPv6 address by 1

Time:12-25

I'm currently experimenting with a little bash script. I have an IPv6 address (via mysql query) in a variable and want to increment it by 1 (by also honoring the IPv6 rules [hex]). Any hint how to achieve this?

Is there a simple way in bash to increment a given address by 1? (this is to avoid duplicates).

Basically: 2001::0000:fe04 is given and I want the script to manipulate the variable to output 2001::0000:fe05, 2001::0000:fe06 and after 2001::0000:fe09 it should be 2001::0000:fe0a - 2001::0000:fe0f followed by 2001::0000:fe10 (hex count). If all ip's are full (2001::0:ffff) it should use the next IP subnet by honoring IPv6 subnetting. So after 2001::0:ffff the next address would be 2001::0001:0001

Hope you understand what I mean ;)

CodePudding user response:

This will add 1 to your ip6 address using the Net::IP perl package.

#!/usr/bin/env perl

use strict;
use Net::IP qw(ip_inttobin ip_bintoip);

my $ip = Net::IP->new('2001::0000:fe05') || die;

print ("IP  : ".$ip->ip()."\n");
print ("Sho : ".$ip->short()."\n");
print ("Int : ".$ip->intip()."\n");

# add 1 to the address
my $next_bin = ip_inttobin($ip->intip   1, $ip->version);
my $next = Net::IP->new(ip_bintoip($next_bin, $ip->version));

print "\nAfter incrementing by 1\n";
print ("IP  : ".$next->ip()."\n");
print ("Sho : ".$next->short()."\n");
$ perl ip6_test.pl 
IP  : 2001:0000:0000:0000:0000:0000:0000:fe05
Sho : 2001::fe05
Int : 42540488161975842760550356425300311557

After incrementing by 1
IP  : 2001:0000:0000:0000:0000:0000:0000:fe06
Sho : 2001::fe06
  • Related