Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add option to use fixed port for testing #47

Merged
merged 1 commit into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading