client: imlement client, fix #4

This commit is contained in:
Aleksandr Razumov
2016-05-09 22:36:11 +03:00
parent ce14f2a81b
commit 76446d1824
3 changed files with 43 additions and 10 deletions

5
client.go Normal file
View File

@@ -0,0 +1,5 @@
package stun
// Client implements STUN client.
type Client struct {
}

View File

@@ -5,22 +5,29 @@ import (
"fmt" "fmt"
"net" "net"
"os" "os"
"strings"
"time" "time"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli" "github.com/codegangsta/cli"
"github.com/cydev/stun" "github.com/cydev/stun"
) )
var ( const (
serverAddress string version = "0.1"
) )
func discover(c *cli.Context) error { func wrapLogrus(f func(c *cli.Context) error) func(c *cli.Context) error {
if !strings.Contains(serverAddress, ":") { return func(c *cli.Context) error {
serverAddress = fmt.Sprintf("%s:%d", serverAddress, stun.DefaultPort) err := f(c)
if err != nil {
logrus.Errorln("discover error:", err)
}
return err
} }
conn, err := net.Dial("udp", serverAddress) }
func discover(c *cli.Context) error {
conn, err := net.Dial("udp", stun.Normalize(c.String("server")))
if err != nil { if err != nil {
return err return err
} }
@@ -31,6 +38,13 @@ func discover(c *cli.Context) error {
} }
m.TransactionID = stun.NewTransactionID() m.TransactionID = stun.NewTransactionID()
m.AddSoftware("cydev/stun alpha") m.AddSoftware("cydev/stun alpha")
m = stun.AcquireFields(stun.Message{
TransactionID: stun.NewTransactionID(),
Type: stun.MessageType{
Method: stun.MethodBinding,
Class: stun.ClassRequest,
},
})
m.WriteHeader() m.WriteHeader()
timeout := 100 * time.Millisecond timeout := 100 * time.Millisecond
for i := 0; i < 9; i++ { for i := 0; i < 9; i++ {
@@ -81,10 +95,9 @@ func main() {
Name: "server", Name: "server",
Value: "ci.cydev.ru", Value: "ci.cydev.ru",
Usage: "STUN server address", Usage: "STUN server address",
Destination: &serverAddress,
}, },
} }
app.Action = discover app.Action = wrapLogrus(discover)
app.Version = version
app.Run(os.Args) app.Run(os.Args)
} }

15
stun.go
View File

@@ -28,12 +28,27 @@ import (
"fmt" "fmt"
"io" "io"
"strconv" "strconv"
"strings"
"sync" "sync"
"github.com/cydev/buffer" "github.com/cydev/buffer"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
// Normalize returns normalized address.
func Normalize(address string) string {
if len(address) == 0 {
address = "0.0.0.0"
}
if !strings.Contains(address, ":") {
address = fmt.Sprintf("%s:%d", address, DefaultPort)
}
return address
}
// DefaultPort is IANA assigned port for "stun" protocol.
const DefaultPort = 3478
const ( const (
// magicCookie is fixed value that aids in distinguishing STUN packets // magicCookie is fixed value that aids in distinguishing STUN packets
// from packets of other protocols when STUN is multiplexed with those // from packets of other protocols when STUN is multiplexed with those