zoukankan      html  css  js  c++  java
  • 汇总下几个IP计算/转换的shell小脚本-转

    原文:http://blog.chinaunix.net/uid-20788470-id-1841646.html
     
    1. IP转换为整数
    > vi ip2num.sh
    #!/bin/bash
    # 所有用到的命令全是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};      # 把点分十进制地址拆成数组(read的-a选项表示把输入读入到数组, 下标从0开始)
    echo $(( ${IP_ARRAY[0]}<<24 | ${IP_ARRAY[1]}<<16 | ${IP_ARRAY[2]}<<8 | ${IP_ARRAY[3]} ));       # bash的$(()) 支持位运算
    HEX_STRING=$(printf "0X%02X%02X%02X%02X " ${IP_ARRAY[0]} ${IP_ARRAY[1]} ${IP_ARRAY[2]} ${IP_ARRAY[3]});     # 这里演示另外一种不使用位运算的方法
    printf "%d " ${HEX_STRING};
    # 参考自:http://hi.baidu.com/test/blog/item/8af8513da98b72eb3d6d9740.html
    # 可以使用mysql的select inet_aton('${IP_ADDR}'); 来验证结果是否正确。

    2. 整数转换为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
    或者
    #!/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. 把掩码长度转换成掩码
    # 可以根据2修改下, 255.255.255.255的整型值是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"
  • 相关阅读:
    VSCode添加git bash作为默认终端
    Git无法提交branch is currently checked out
    Excel创建下拉列表限制数据有效性
    Windows添加管理员用户
    从Windows10中彻底删除【3D对象】文件夹
    异常处理机制
    泛型
    Java集合
    String、StringBuffer、StringBulider
    System类与Runtime类
  • 原文地址:https://www.cnblogs.com/mude918/p/ip.html
Copyright © 2011-2022 走看看