douyun8674 2017-01-16 05:47
浏览 279
已采纳

在Golang中获取公共IP

How do we get public IP in golang? Method req.Header.Get("X-Forwarded-For") returns array of IPs. How do we identify which one is public and which on internal? Is there any other method to fetch public(external) IP?

  • 写回答

2条回答 默认 最新

  • dousaoxiancy199896 2017-01-16 06:26
    关注

    The following IP blocks are reserved for private IP addresses.

    Class        Starting IPAddress    Ending IP Address    # of Hosts
    A            10.0.0.0              10.255.255.255       16,777,216
    B            172.16.0.0            172.31.255.255       1,048,576
    C            192.168.0.0           192.168.255.255      65,536
    Link-local-u 169.254.0.0           169.254.255.255      65,536
    Link-local-m 224.0.0.0             224.0.0.255          256
    Local        127.0.0.0             127.255.255.255      16777216
    

    You may write a function that checks for if the ip comes under these

    Here is an attempt to do the same,the code below is not handling ipv6 please add if needed

    func IsPublicIP(IP net.IP) bool {
        if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
            return false
        }
        if ip4 := IP.To4(); ip4 != nil {
            switch {
            case ip4[0] == 10:
                return false
            case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
                return false
            case ip4[0] == 192 && ip4[1] == 168:
                return false
            default:
                return true
            }
        }
        return false
    }
    

    Here is play link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 谁会做这个啊#ensp#Boson NetSim
  • ¥15 如何编写针对TPS6503320FRGE型号的电源管理芯片的编程代码?
  • ¥15 设计简单目录管理系统,要满足以下内容
  • ¥15 关于九十度混合耦合器信号分析问题
  • ¥15 Cesm如何关闭不用的模块呢
  • ¥15 vue2两层数据导出为excle
  • ¥15 有人能帮我做一下这个项目吗
  • ¥15 网络上传速率比下载速率高
  • ¥15 (标签-游戏|关键词-网页游戏)
  • ¥15 这个咋搞🥹可能需要手把手教