Summarize several small shell scripts for IP calculation/conversion - turn

Original text: http://blog.chinaunix.net/uid-20788470-id-1841646.html
 
1. Convert IP to integer
> vi ip2num.sh
#!/bin/bash
# All commands used are built-in commands of bash
IP_ADDR=$1
[[ "$IP_ADDR" =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] || { echo "ip format error."; exit 1; }
IP_LIST=${IP_ADDR//./ };
read -a IP_ARRAY <<<${IP_LIST}; # Split the dotted decimal address into an array (the -a option of read means to read the input into an array, and the subscript starts from 0 Start)
echo $(( ${IP_ARRAY[0]}<<24 | ${IP_ARRAY[1]}<<16 | ${IP_ARRAY[2]}<<8 | ${IP_ARRAY[3]} )); # bash $(()) supports bitwise operations
HEX_STRING=$(printf "0X%02X%02X%02X%02X\n" ${IP_ARRAY[0]} ${IP_ARRAY[1]} ${IP_ARRAY[2]} ${IP_ARRAY[3]}); # here Demonstrate another method that does not use bitwise operations
printf "%d\n" ${HEX_STRING};
# Reference from: http://hi.baidu.com/test/blog/item/8af8513da98b72eb3d6d9740.html
# You can use mysql's select inet_aton('${IP_ADDR}'); to verify that the result is correct.

2. Convert integer to IP
> vi num2ip.sh
#!/bin/bash
N=$1
H1=$(($N & 0x000000ff))
H2=$((($N & 0x0000ff00) >> 8))
L1=$((($N & 0x00ff0000) >> 16))
L2=$((($N & 0xff000000) >> 24))
echo $L2.$L1.$H2.$H1
or
#!/bin/bash
N=$1
declare -i H1="$N & 0x000000ff"
declare -i H2="($N & 0x0000ff00) >> 8"
declare -i L1="($N & 0x00ff0000) >> 16"
declare -i L2="($N & 0xff000000) >> 24"
echo "$L2.$L1.$H2.$H1"
# The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION ) is performed when the variable is assigned a value.
# 参考自: https://dream4ever.org/archive/t-263202.html

3. Convert the mask length to mask
# It can be modified according to 2, the integer value of 255.255.255.255 is 4294967295
#!/bin/bash
declare -i FULL_MASK_INT=4294967295
declare -i MASK_LEN=$1
declare -i LEFT_MOVE="32 - ${MASK_LEN}"
declare -i N="${FULL_MASK_INT} << ${LEFT_MOVE}"
declare -i H1="$N & 0x000000ff"
declare -i H2="($N & 0x0000ff00) >> 8"
declare -i L1="($N & 0x00ff0000) >> 16"
declare -i L2="($N & 0xff000000) >> 24"
echo "$L2.$L1.$H2.$H1"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324828384&siteId=291194637