2023-09-20 20:05:29 +02:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
2023-11-22 11:41:54 +01:00
|
|
|
"encoding/json"
|
|
|
|
"io"
|
2023-09-20 20:05:29 +02:00
|
|
|
"log"
|
|
|
|
"net"
|
2023-11-22 11:41:54 +01:00
|
|
|
"net/http"
|
2023-09-20 20:05:29 +02:00
|
|
|
)
|
|
|
|
|
2023-10-26 17:53:12 +02:00
|
|
|
// GetOutboundIP: gets the oubound IP of this packet
|
2023-09-20 20:05:29 +02:00
|
|
|
func GetOutboundIP() net.IP {
|
|
|
|
conn, err := net.Dial("udp", "8.8.8.8:80")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
|
|
|
return localAddr.IP
|
|
|
|
}
|
2023-11-22 11:41:54 +01:00
|
|
|
|
|
|
|
const IP_SERVICE = "https://api.ipify.org?format=json"
|
|
|
|
|
|
|
|
type IpResponse struct {
|
|
|
|
Ip string `json:"ip"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *IpResponse) GetIP() net.IP {
|
|
|
|
return net.ParseIP(i.Ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetPublicIP: get the nodes public IP address. For when a node is behind NAT
|
|
|
|
func GetPublicIP() (net.IP, error) {
|
|
|
|
req, err := http.NewRequest(http.MethodGet, IP_SERVICE, nil)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
resBody, err := io.ReadAll(res.Body)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var jsonResponse IpResponse
|
|
|
|
|
|
|
|
err = json.Unmarshal([]byte(resBody), &jsonResponse)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return jsonResponse.GetIP(), nil
|
|
|
|
}
|