Created
November 1, 2014 00:46
-
-
Save Mistobaan/94226e44c50e9bb92b15 to your computer and use it in GitHub Desktop.
Check if there is an interface with a given name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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\n", 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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment