Skip to content

Instantly share code, notes, and snippets.

@TimaGribanov
Created October 24, 2019 13:16
Show Gist options
  • Save TimaGribanov/f203b9b27b9ca61829c9b5ae7fd6328c to your computer and use it in GitHub Desktop.
Save TimaGribanov/f203b9b27b9ca61829c9b5ae7fd6328c to your computer and use it in GitHub Desktop.
Converting IPs
#!/bin/bash
#Converting decimal to binary
##Source: https://stackoverflow.com/questions/55239476/awk-convert-decimal-to-binary
gawk '
function d2b(d, b) {
while(d) {
b=d%2b
d=int(d/2)
}
return(b)
}
{
print d2b($0)
}' $1 > temp_bin
#Parsing octets
gawk '{ print substr($1,1,8) "." substr($1,9,8) "." substr($1,17,8) "." substr($1,25,8) }' temp_bin > temp_bin_parsed
#Converting binary to decimal
gawk -F "." '{
a=((substr($1,1,1)*128)+(substr($1,2,1)*64)+(substr($1,3,1)*32)+(substr($1,4,1)*16)+(substr($1,5,1)*8)+(substr($1,6,1)*4)+(substr($1,7,1)*2)+(substr($1,8,1)))
b=((substr($2,1,1)*128)+(substr($2,2,1)*64)+(substr($2,3,1)*32)+(substr($2,4,1)*16)+(substr($2,5,1)*8)+(substr($2,6,1)*4)+(substr($2,7,1)*2)+(substr($2,8,1)))
c=((substr($3,1,1)*128)+(substr($3,2,1)*64)+(substr($3,3,1)*32)+(substr($3,4,1)*16)+(substr($3,5,1)*8)+(substr($3,6,1)*4)+(substr($3,7,1)*2)+(substr($3,8,1)))
d=((substr($4,1,1)*128)+(substr($4,2,1)*64)+(substr($4,3,1)*32)+(substr($4,4,1)*16)+(substr($4,5,1)*8)+(substr($4,6,1)*4)+(substr($4,7,1)*2)+(substr($4,8,1)))
print a "." b "." c "." d
}' temp_bin_parsed > decimal2ip_result.txt
rm temp_bin temp_bin_parsed
#!/bin/bash
gawk -F "." '{
print (($1*256*256*256)+($2*256*256)+($3*256)+$4)
}' $1 > ip2decimal_result.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment