dongsibao8977 2014-10-31 20:46
浏览 42
已采纳

去检查EC2环境? 还是DNS域名?

I want to see if the program is being run in EC2 or not.

One way is to run hostname -d in EC2 to get the DNS domain name.

How do I get this DNS domain name in Go.

I looked at the net package using http://golang.org/pkg/net/#LookupNS

But I need to pass an argument.

How do I check if it's in EC2 or not?

Thanks

  • 写回答

2条回答 默认 最新

  • dongxing1412 2014-11-01 00:45
    关注

    You can see if there is an interface with a specific name with this function:

    package main
    
    import (
        "log"
        "net"
        "strings"
    )
    
    func trace(fmt string, args ...interface{}) {
        log.Printf(fmt, args...)
    }
    
    func HasAddrWithName(name string) (bool, error) {
        ifaces, err := net.Interfaces()
        if err != nil {
            return false, err
        }
        for _, iface := range ifaces {
            addrs, err := iface.Addrs()
            if err != nil {
                trace("%s", err)
                continue
            }
            for _, addr := range addrs {
                ipaddr, _, err := net.ParseCIDR(addr.String())
                if err != nil {
                    trace("%s", err)
                    continue
                }
                hosts, err := net.LookupAddr(ipaddr.String())
                if err != nil {
                    trace("%s", err)
                    continue
                }
                for idx, h := range hosts {
                    trace("%d: %s
    ", idx, h)
                    if strings.Contains(h, name) {
                        return true, nil
                    }
                }
            }
        }
        return false, nil
    }
    
    func main() {
        hasAddr, err := HasAddrWithName(".ec2.internal")
        if err != nil {
            log.Fatal(err)
        }
        if hasAddr {
            log.Println("inside ec2")
            return
        }
    
        log.Println("Not inside ec2")
    }
    

    The function will try to find all the interface an resolve the ip to a dns name. if the name contains the specific string returns true.

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

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?