把ip地址转换为二进制的bash脚本
# 几个关键点:
# # tr 替换字符串 # 循环遍历ip的每一位 # echo 指明 编码类型为二进制, 然后借助 bc 计算二级制的值 # TODO 从循环到awk的管道 没完全理解 # awk printf 的格式表示 为每个8为的二进制比特位前面加上"." # "cut -c 2-" 表示 "Cut out everything from the 2rd character to the end of each line" function ip2binary() { if [ $# -eq 0 ]; then echo "example"; echo "ip_2_binary 192.168.31.178"; echo "11000000.10101000.00011111.10110010"; return 1; fi local ip=$1 for i in $(echo ${ip} | tr '.' ' '); do echo "obase=2 ; $i" | bc; done | awk '{printf ".%08d", $1}' | cut -c 2- }
ref: https://stackoverflow.com/questions/4042601/unixhow-to-convert-ip-address-to-binary-code