Networking 如何从IP获取主机
我正在研究一个计算IP的十进制等价物的函数,为了得到结果,我使用以下公式:Networking 如何从IP获取主机,networking,ip,Networking,Ip,我正在研究一个计算IP的十进制等价物的函数,为了得到结果,我使用以下公式: decimal = ((octet1 * 16777216) + (octet2 * 65536) + (octet13 * 256) + (octet4)) 有人知道如何逆转这个过程吗?我的意思是,如何从十进制数中获得IP地址 我在寻找一些数学公式,我已经知道了nslookup命令 提前谢谢 十进制: 到八位字节: 使用1.2.3.4 使用Go实现 十进制: 到八位字节: 使用1.2.3.4 使用
decimal = ((octet1 * 16777216) + (octet2 * 65536) + (octet13 * 256) + (octet4))
有人知道如何逆转这个过程吗?我的意思是,如何从十进制数中获得IP地址
我在寻找一些数学公式,我已经知道了nslookup
命令
提前谢谢 十进制:
到八位字节:
使用1.2.3.4
使用Go实现
十进制:
到八位字节:
使用1.2.3.4
使用Go实现
乘法和除法是对计算能力的浪费。请记住,您正在处理位模式: o1.o2.o3.o4至数字:
n = o1<<24 | o2<<16 | o3<<8 | o4
乘法和除法是对计算能力的浪费。请记住,您正在处理位模式: o1.o2.o3.o4至数字:
n = o1<<24 | o2<<16 | o3<<8 | o4
decimal = (1 * 256^3) + (2 * 256^2) + (3 * 256^1) + 4
decimal = 16909060
octet1 = Floor(16909060 / 256^3)
octet1 = 1
octet2 = Floor((16909060 - (1 * 256^3)) / 256^2)
octet2 = 2
octet3 = Floor((16909060 - (1 * 256^3) - (2 * 256^2)) / 256^1)
octet3 = 3
octet4 = 16909060 - (1 * 256^3) - (2 * 256^2) - (3 * 256^1)
octet4 = 4
package main
import (
"errors"
"flag"
"fmt"
"math"
"os"
"strconv"
"strings"
)
var (
ip = flag.String("i", "", "IP address in dotted notation")
dec = flag.Int("d", 0, "IP address in decimal notation")
)
func ipv4ToDec(ip string) (int, error) {
var result int
octets := strings.Split(ip, ".")
if len(octets) != 4 {
return 0, errors.New("IP should consist of 4 '.' seperated numbers")
}
for i := 0; i < 4; i++ {
v, err := strconv.Atoi(octets[3-i])
if err != nil {
return 0, errors.New("unable to convert octet to number")
}
if v < 0 || v > 255 {
return 0, errors.New("octet should be between 0 and 255")
}
result += v * int(math.Pow(256, float64(i)))
}
return result, nil
}
func decToIpv4(dec int) (string, error) {
var octets []string
for i := 0; i < 4; i++ {
octet := dec / int(math.Pow(256, float64(3-i)))
if octet > 255 {
return "", errors.New("octet larger than 255")
}
dec -= octet * int(math.Pow(256, float64(3-i)))
octets = append(octets, strconv.Itoa(octet))
}
return strings.Join(octets, "."), nil
}
func main() {
flag.Parse()
if ((*ip != "" && *dec != 0) || (*ip == "" && *dec == 0)) {
fmt.Println("Use either -i or -d.")
os.Exit(1)
}
if *ip != "" {
result, err := ipv4ToDec(*ip)
if err != nil {
fmt.Println("Conversion failed: ", err)
os.Exit(1)
}
fmt.Println(result)
}
if *dec != 0 {
result, err := decToIpv4(*dec)
if err != nil {
fmt.Println("Conversion failed: ", err)
os.Exit(1)
}
fmt.Println(result)
}
}
$ ./ip-conv -i 1.2.3.4
16909060
$ ./ip-conv -d 16909060
1.2.3.4
$ ./ip-conv -i 192.168.0.1
3232235521
# Using the output of IP->decimal as input to decimal->IP
$ ./ip-conv -d $(./ip-conv -i 192.168.0.1)
192.168.0.1
n = o1<<24 | o2<<16 | o3<<8 | o4
o1 = n>>24
o2 = (n>>16) & 255
o3 = (n>>8) & 255
o4 = n & 255