Skip to content

Instantly share code, notes, and snippets.

@uablrek
Created September 11, 2022 16:50
Show Gist options
  • Select an option

  • Save uablrek/0bacf99d8faf8ade4666c02dcd28774c to your computer and use it in GitHub Desktop.

Select an option

Save uablrek/0bacf99d8faf8ade4666c02dcd28774c to your computer and use it in GitHub Desktop.
List IP addresses
package main
import (
"fmt"
"log"
"net"
"os"
"strings"
)
func main() {
if len(os.Args) > 1 {
printAddrs(GetLocalAddresses(os.Args[1]))
} else {
printAddrs(GetAllLocalAddresses())
}
}
func GetAllLocalAddresses() []net.Addr {
addr, err := net.InterfaceAddrs()
if err != nil {
log.Fatalln("InterfaceAddrs:", err)
}
return addr
}
func GetLocalAddresses(dev string) []net.Addr {
ifi, err := net.InterfaceByName(dev)
if err != nil {
log.Fatalln("InterfaceByName:", err)
}
addr, err := ifi.Addrs()
if err != nil {
log.Fatalln("Addrs:", err)
}
return addr
}
func printAddrs(addr []net.Addr) {
for _, a := range addr {
ipstr := strings.Split(a.String(), "/")[0]
ip := net.ParseIP(ipstr)
if ip == nil {
log.Fatalln("Parse failed:", ipstr)
}
if isValidForSet(ip) {
fmt.Println(ip)
}
}
}
func isValidForSet(ip net.IP) bool {
if ip.To4() == nil && ip.IsLinkLocalUnicast() {
return false
}
if ip.IsLoopback() {
return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment