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

15
stun.go
View File

@@ -28,12 +28,27 @@ import (
"fmt"
"io"
"strconv"
"strings"
"sync"
"github.com/cydev/buffer"
"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 (
// magicCookie is fixed value that aids in distinguishing STUN packets
// from packets of other protocols when STUN is multiplexed with those