checkaayush
11/25/2018 - 11:29 AM

Get your public and private IP addresses with one command

Get your public and private IP addresses with one command

// Utility to get your public and private IP addresses
// Usage:
// 1. Run: go build -o myip myip.go
// 2. Add the executable myip to your PATH
// 3. Run: myip

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
)

// GetPublicIP returns your public IP address
func GetPublicIP() string {
	resp, err := http.Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	ip := string(body)
	return ip
}

// GetPrivateIP returns your preferred outbound private IP address
func GetPrivateIP() string {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)
	ip := localAddr.IP.String()

	return ip
}

func main() {
	fmt.Printf("Public IP: %s\nPrivate IP: %s\n", GetPublicIP(), GetPrivateIP())
}