Golang Ip地址字符串整数string Int相互转换


本文摘自网络,作者,侵删。


title: "Golang Ip地址字符串整数string Int相互转换"
date: 2021-01-29T21:06:57+08:00
draft: true
tags: ['go']
author: "dadigang"
author_cn: "大地缸"
personal: "http://www.real007.cn"


关于作者

http://www.real007.cn/about

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

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


本文来自:简书

感谢作者:大地缸

查看原文:Golang Ip地址字符串整数string Int相互转换

相关阅读 >>

grpc-quick start

Golang在kubernetes语境下的编程范式

Go怎么实现字符串首字母大、小写函数

Golang不适合开发web吗

Golang中...是什么意思?

聊聊dubbo-Go-proxy的parammapper

Golang 架构设计原则 单一职责原则

Go modules构建项目

一文搞懂如何实现 Go 超时控制

完全掌握Go的pprof使用方法

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...