IP Address Converter

后端 未结 7 1101
臣服心动
臣服心动 2020-12-29 11:17

There is IP address: 66.102.13.19, and from this address as that received this address

http://1113984275

But how? And how I can make this

7条回答
  •  渐次进展
    2020-12-29 11:50

    Binary shifting is always faster than multiplying or dividing.
    Using a binary AND is faster than mod.

    ip2dec(){ # Convert an IPv4 IP number to its decimal equivalent.
              declare -i a b c d;
              IFS=. read a b c d <<<"$1";
              echo "$(((a<<24)+(b<<16)+(c<<8)+d))";
            }
    dec2ip(){ # Convert an IPv4 decimal IP value to an IPv4 IP.
              declare -i a=$((~(-1<<8))) b=$1; 
              set -- "$((b>>24&a))" "$((b>>16&a))" "$((b>>8&a))" "$((b&a))";
              local IFS=.;
              echo "$*";
            }
    
    ip=66.102.13.19
    a=$(ip2dec "$ip")
    b=$(dec2ip "$a")
    echo "$ip DecIP=$a IPv4=$b "
    

    Note: This system will fail with values like 0008.
    Bash thinks it is an octal number.

    To solve that, each value will have to be cleaned with something like:

    IsDecInt()(     # Is the value given on $1 a decimal integer (with sign)?
                    declare n=$1; set --
                    if [[ $n =~ ^([+-]?)((0)|0*([0-9]*))$ ]]; then
                        set -- "${BASH_REMATCH[@]:1}"
                    else
                        exit 1
                    fi
                    echo "$1$3$4";
              )
    
      a=$(IsDecInt "$a")||{ Echo "Value $a is not an integer" >&2; exit 1; }
    

    For (very) old shells: bash since 2.04, or dash or any (reasonable) shell:

    ip2dec(){ # Convert an IPv4 IP number to its decimal equivalent.
              local a b c d;
              IFS=. read a b c d <<-_EOF_
    $1
    _EOF_
              echo "$(((a<<24)+(b<<16)+(c<<8)+d))";
            }
    
    dec2ip(){   # Convert an IPv4 decimal IP value to an IPv4 IP.
                local a=$((~(-1<<8))) b=$1; 
                set -- "$((b>>24&a))" "$((b>>16&a))" "$((b>>8&a))" "$((b&a))";
                local IFS=.;
                echo "$*";
            }
    
    ip=$1
    a=$(ip2dec "$ip")
    b=$(dec2ip "$a")
    echo "$ip DecIP=$a IPv4=$b "
    

提交回复
热议问题