Skip to content

Commit

Permalink
feat: add option to use fixed port for testing (#47)
Browse files Browse the repository at this point in the history
Signed-off-by: Liang Deng <[email protected]>
  • Loading branch information
YTGhost authored Aug 30, 2023
1 parent fe603b7 commit 293c9ea
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

func main() {
var serverAddr = flag.String("s", stun.DefaultServerAddr, "STUN server address")
var localPort = flag.Int("p", 0, "The port on which to bind requests, set to 0 to pick a random port")
var behaviorTestMode = flag.Bool("b", false, "Enable NAT behavior test mode")
var verboseLevel = flag.Int("v", 0, "Verbose level (0: none, 1: verbose, 2: double verbose, 3: triple verbose)")
flag.Parse()
Expand All @@ -37,6 +38,7 @@ func main() {
// Create a STUN client
client := stun.NewClient()
client.SetServerAddr(*serverAddr)
client.SetLocalPort(*localPort)
client.SetVerbose(*verboseLevel >= 1)
client.SetVVerbose(*verboseLevel >= 2)

Expand Down
16 changes: 15 additions & 1 deletion stun/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package stun

import (
"errors"
"fmt"
"net"
"strconv"
)
Expand All @@ -24,6 +25,7 @@ import (
// to discover NAT type.
type Client struct {
serverAddr string
localPort int
softwareName string
conn net.PacketConn
logger *Logger
Expand Down Expand Up @@ -70,6 +72,11 @@ func (c *Client) SetServerAddr(address string) {
c.serverAddr = address
}

// SetLocalPort allows user to set the local port to send request.
func (c *Client) SetLocalPort(port int) {
c.localPort = port
}

// SetSoftwareName allows user to set the name of the software, which is used
// for logging purpose (NOT used in the current implementation).
func (c *Client) SetSoftwareName(name string) {
Expand All @@ -90,7 +97,14 @@ func (c *Client) Discover() (NATType, *Host, error) {
// create a connection and close it at the end.
conn := c.conn
if conn == nil {
conn, err = net.ListenUDP("udp", nil)
var laddr *net.UDPAddr
if c.localPort != 0 {
laddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", c.localPort))
if err != nil {
return NATError, nil, err
}
}
conn, err = net.ListenUDP("udp", laddr)
if err != nil {
return NATError, nil, err
}
Expand Down

0 comments on commit 293c9ea

Please sign in to comment.