Go language to get public IP address

 1 minute to read

go language to get the public IP address

Here are two ways

  1. Request the stun server to obtain
  2. Request https://api.ipify.org to get

code show as below:

package main

import (
	"fmt"
	"github.com/pion/stun"
	"io/ioutil"
	"net/http"
)

func main() {
	// Creating a "connection" to STUN server.
	c, err := stun.Dial("udp", "stun.stunprotocol.org:3478")
	if err != nil {
		panic(err)
	}
	// Building binding request with random transaction id.
	message := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
	// Sending request to STUN server, waiting for response message.
	if err := c.Do(message, func(res stun.Event) {
		if res.Error != nil {
			panic(res.Error)
		}
		fmt.Println(res.Message)
		// Decoding XOR-MAPPED-ADDRESS attribute from message.
		var xorAddr stun.XORMappedAddress
		if err := xorAddr.GetFrom(res.Message); err != nil {
			panic(err)
		}

		fmt.Println("your IP is", xorAddr.IP)
	}); err != nil {
		panic(err)
	}

	
	res, _ := http.Get("https://api.ipify.org")
	ip, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(ip))
}