Skip to content

Instantly share code, notes, and snippets.

@mdijoux
Last active August 4, 2022 04:35
Show Gist options
  • Save mdijoux/05c427e3b162943059ad41f39ee38ac0 to your computer and use it in GitHub Desktop.
Save mdijoux/05c427e3b162943059ad41f39ee38ac0 to your computer and use it in GitHub Desktop.
Offset IP
###################################################
# Offset an IP address by any number of addresses #
###################################################
offset_ip(){
IP=$1
OFFSET=$2
# Convert IP as hexadecimal number
IP_HEX=$(printf '%.2X%.2X%.2X%.2X\n' `echo $IP | sed -e 's/\./ /g'`)
# Add the offset to the IP hexadecimal representation
NEXT_IP_HEX=$(printf %.8X `echo $(( 0x$IP_HEX + $OFFSET ))`)
# Print the result from hexadecimal representation back to IP string representation
printf '%d.%d.%d.%d\n' `echo $NEXT_IP_HEX | sed -r 's/(..)/0x\1 /g'`
}
# Examples
# $ offset_ip 192.168.1.2 20
# 192.168.1.22
# $ offset_ip 192.168.1.2 257
# 192.168.2.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment