暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Golang IP 地址字符串整数/string int 相互转换

进击的代码 2021-05-31
2410

概览

Go 中没有 C 语言 inet_aton
inet_ntoa
类似的转换 IP 函数,

所以需要手动封装两个函数

(转换的方法有多种,我选择了简洁的)

实现

package main

import (
"fmt"
"math/big"
"net"
)

func InetNtoA(ip int64) string {
return fmt.Sprintf("%d.%d.%d.%d",
byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}

func InetAtoN(ip string) int64 {
ret := big.NewInt(0)
ret.SetBytes(net.ParseIP(ip).To4())
return ret.Int64()
}

func main() {
ip := "192.168.78.123"
ipInt := InetAtoN(ip)

fmt.Printf("convert string ip [%s] to int: %d\n", ip, ipInt)
fmt.Printf("convert int ip [%d] to string: %s\n", ipInt, InetNtoA(ipInt))
}

复制

注:InetAtoN
最好加安全验证,检查 IP 字符串的有效性, 可以判断 net.ParseIP(ip).To4()
是否为 nil

运行效果

可以使用 ping 命令简单验证一下转换的结果

文章转载自进击的代码,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论