Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ydnar
Created April 17, 2020 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydnar/6c8c164a092900110c17d4e0f42604b8 to your computer and use it in GitHub Desktop.
Save ydnar/6c8c164a092900110c17d4e0f42604b8 to your computer and use it in GitHub Desktop.
Get Tailscale IP from terminal
package main
import (
"flag"
"fmt"
"net"
"os"
)
func main() {
var ipv4 bool
var ipv6 bool
var all bool
var up bool
flag.BoolVar(&ipv4, "4", true, "print IPv4")
flag.BoolVar(&ipv6, "6", false, "print IPv6")
flag.BoolVar(&all, "all", false, "print IPv4 and IPv6")
flag.BoolVar(&up, "up", true, "only print interfaces that are currently up")
flag.Parse()
if all {
ipv4 = true
ipv6 = true
}
interfaces, err := net.Interfaces()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
for _, i := range interfaces {
// Ignore hardware interfaces.
if i.HardwareAddr != nil {
continue
}
// Ignore interfaces that aren’t tunnels.
if i.Flags&net.FlagPointToPoint == 0 {
continue
}
// Ignore interfaces that are down.
if up && i.Flags&net.FlagUp == 0 {
continue
}
addrs, err := i.Addrs()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
continue
}
for j, addr := range addrs {
ipnet, ok := addr.(*net.IPNet)
if !ok {
fmt.Fprintf(os.Stderr, "Error: interface %s addr %d is not an IP network ", i.Name, j)
continue
}
is4 := ipnet.IP.To4() != nil
if (is4 && !ipv4) || (!is4 && !ipv6) {
continue
}
fmt.Fprintf(os.Stderr, "Interface %s addr %d: ", i.Name, j)
fmt.Print(ipnet.IP.String())
fmt.Fprint(os.Stderr, "\n")
}
}
}
@ydnar
Copy link
Author

ydnar commented Apr 17, 2020

It only prints the IPs to stdout, so you can run go run main.go | pbcopy to get the Tailscale IPv4 address on the pasteboard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment