IP地址转换器 [英] IP Address Converter

查看:130
本文介绍了IP地址转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有是IP地址:66.102.13.19,并从该地址作为接收到该地址

 的http:// 1113984275

但如何?以及我如何使用bash的帮助使这个。
例如,这项服务可以做到这一点,但我不明白的算法。


解决方案

  IP = 66.102.13.19
IFS =。阅读-r A B C D<<< $ IP
printf的'%s的%d个\\ N'的http://$((A * 256 ** 3 + B * 256 ** 2 + C * 256 + D))

顺便说一句,在你的问题的数量不匹配的IP地址。

要一个十进制转换为IP:

 #!/斌/庆典
dec2ip(){
    本地IP DEC = $ @
    为电子商务在{} 3..0
    做
        ((八位字节= DEC /(256 ** E)))
        ((十二月 - =八位* 256 ** e)条)
        IP + = $ $ DELIM八位
        DELIM =。
    DONE
    printf的'%s的\\ n'$ IP
}dec2ip$ @

要一个IP转换为十进制:

 #!/斌/庆典
ip2dec(){
    本地A B C D IP = $ @
    IFS =。阅读-r A B C D<<< $ IP
    printf的%d个\\ N'$((A * 256 ** 3 + B * 256 ** 2 + C * 256 + D))
}ip2dec$ @

演示:

  $ ./dec2ip 1113984275
66.102.13.19$ ./ip2dec 66.102.13.19
1113984275

这两个脚本依赖于不在一些伯恩衍生弹present猛砸功能。以下是AWK版本改用:

 #!的/ usr /斌/的awk -f
#dec2ip
开始 {
    DEC = ARGV [1]
    对于(E = 3; e基= 0; E--){
        八位字节= INT(DEC /(256 ^ E))
        十二月 - =八位* 256 ^ E
        IP = IP DELIM八位
        DELIM =。
    }
    的printf(%S \\ n,IP)
}

 #!的/ usr /斌/的awk -f
#ip2dec
开始 {
    IP = ARGV [1]
    拆分(IP,八位,。)
    对于(i = 1; I< = 4;我++){
        十二月+ =八位[I] * 256 **(4 - I)
    }
    的printf(%I \\ N,DEC)
}

它们可以以相同的方式被称为如上述的击脚本。

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 with the help of bash. For example, this service can do it, but I do not understand the algorithm.

解决方案

ip=66.102.13.19
IFS=. read -r a b c d <<< "$ip"
printf '%s%d\n' "http://" "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"

By the way, the number in your question doesn't match the IP address.

To convert a decimal to an IP:

#!/bin/bash
dec2ip () {
    local ip dec=$@
    for e in {3..0}
    do
        ((octet = dec / (256 ** e) ))
        ((dec -= octet * 256 ** e))
        ip+=$delim$octet
        delim=.
    done
    printf '%s\n' "$ip"
}

dec2ip "$@"

To convert an IP to a decimal:

#!/bin/bash
ip2dec () {
    local a b c d ip=$@
    IFS=. read -r a b c d <<< "$ip"
    printf '%d\n' "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
}

ip2dec "$@"

Demo:

$ ./dec2ip 1113984275
66.102.13.19

$ ./ip2dec 66.102.13.19
1113984275

These two scripts rely on features of Bash that aren't present in some Bourne-derived shells. Here are AWK versions to use instead:

#!/usr/bin/awk -f
# dec2ip
BEGIN {
    dec = ARGV[1]
    for (e = 3; e >= 0; e--) {
        octet = int(dec / (256 ^ e))
        dec -= octet * 256 ^ e
        ip = ip delim octet
        delim = "."
    }
    printf("%s\n", ip)
}

and

#!/usr/bin/awk -f
# ip2dec
BEGIN {
    ip = ARGV[1]
    split(ip, octets, ".")
    for (i = 1; i <= 4; i++) {
        dec += octets[i] * 256 ** (4 - i)
    }
    printf("%i\n", dec)
}

They can be called in the same manner as the Bash scripts above.

这篇关于IP地址转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆