mirror of
https://github.com/tim-beatham/smegmesh.git
synced 2025-08-17 00:21:06 +02:00
25-modify-code-to-use-public-api
Modify the code to use a public IP address by default if none is specified
This commit is contained in:
@ -1,8 +1,11 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// GetOutboundIP: gets the oubound IP of this packet
|
||||
@ -15,3 +18,44 @@ func GetOutboundIP() net.IP {
|
||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
||||
return localAddr.IP
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
Reference in New Issue
Block a user