Created
July 5, 2025 06:16
-
-
Save HirbodBehnam/f7e82a68b0c9fe636026c5ba8771bfa1 to your computer and use it in GitHub Desktop.
Ask the public address of a port from STUN server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net" | |
"os" | |
"time" | |
"github.com/pion/stun" | |
) | |
func main() { | |
// Create a socket on a port | |
localAddress := os.Args[1] | |
fmt.Println("Listening on", localAddress) | |
udpLocalAddress, err := net.ResolveUDPAddr("udp", localAddress) | |
if err != nil { | |
panic(err) | |
} | |
dialer := net.Dialer{ | |
LocalAddr: udpLocalAddress, | |
} | |
conn, err := dialer.Dial("udp", "stun.l.google.com:19302") | |
if err != nil { | |
panic(err) | |
} | |
// Creating a "connection" to STUN server. | |
c, err := stun.NewClient(conn) | |
if err != nil { | |
panic(err) | |
} | |
// In a loop, just ask for IP/Port | |
for { | |
// 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) | |
} | |
// 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) | |
fmt.Println("Your port is", xorAddr.Port) | |
}); err != nil { | |
panic(err) | |
} | |
// Do not get us banned | |
time.Sleep(5 * time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment