Reputation: 1
I have just started with bash scripting and there is a small problem which I have to solve to go on:
I'm getting an IPv6 address in this format:
1080::8:800:200C:417A
Now I want to convert the short into the long IPv6 form like: 1080:0:0:0:8:800:200C:417A
Is there a regex expression or something similar to convert that?
I am working on a docker container which runs on CentOS.
Upvotes: 0
Views: 1194
Reputation: 695
Here is how I decompress IPv6 address.
#!/bin/bash
decompress_ipv6_address() {
# How many hextets are there
num_hextets=${addr//[^:]/}
num_hextets=${#num_hextets}
# Fix up beginning and end
[[ $addr =~ ^:: ]] && addr='0'$addr
[[ $addr =~ ::$ ]] && addr=$addr'0'
# Create additional hextets
additional_hextets=':'
for (( i=$num_hextets; $i<8; i++ ))
do
additional_hextets=$additional_hextets'0:'
done
# Insert additional hextets (replace ::)
addr=${addr/::/$additional_hextets}
}
Upvotes: 1
Reputation: 111
#!/bin/bash
echo "enter the ip address:"
read s
if [[ $s =~ ^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$ ]]; then
echo -e '\E[47;31m'"\033[1mIPv6 Format\033[0m"
echo -n "The IPv6 Address Expanded Form:"
EXPANDED=`sipcalc $s | fgrep Expand | cut -d '-' -f 2`
echo -e "\033[32m $EXPANDED\033[0m"
echo -n "IPv6 address Compress Form:"
Compress=`sipcalc $s | fgrep Comp | cut -d '-' -f 2`
echo -e "\033[32m$Compress\033[0m"
echo -n "Address Type of IPv6:"
type=`sipcalc $s | fgrep type | cut -d '-' -f 2,3,4`
comment=`sipcalc $s | fgrep Comment | cut -d '-' -f 2`
echo -e "\033[32m $type$comment\033[0m"
else
echo -e '\E[37;44m'"\033[1mNOT VALID IPv6 address\033[0m"
fi
This is my code for ipv6 validation.U will get the expanded form of ip using "sipcalc".but you should do some grep and cut commands
Upvotes: 1
Reputation: 10602
It isn't a regex, but it is 'something similar' and it does the job: (tested with python3.5.1)
>>> import ipaddress
>>> x = '1080::8:800:200C:417A'
>>> y = ipaddress.ip_address(x)
>>> y.exploded
'1080:0000:0000:0000:0008:0800:200c:417a'
>>>
Reference: https://docs.python.org/3/library/ipaddress.html
Upvotes: 3