Skip to content

Commit

Permalink
Add parseFromHostport to help parse out localAddr ip
Browse files Browse the repository at this point in the history
  • Loading branch information
film42 committed Jul 22, 2017
1 parent 485c9a2 commit 5fb86aa
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
22 changes: 22 additions & 0 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -97,6 +98,27 @@ func (c *connection) Close() {
logger.Info.Println(c.id, "Connection closed.")
}

func parseAddrFromHostport(hostport string) (string, error) {
if len(hostport) == 0 {
return "", errors.New("Hostport string provided was empty.")
}

colonIndex := strings.IndexByte(hostport, ':')
if colonIndex == -1 {
return "", errors.New("No colon was provided in the net.Conn local address (hostport string).")
}

if i := strings.Index(hostport, "]:"); i != -1 {
return hostport[:i+len("]")], nil
}

if strings.Contains(hostport, "]") {
return "", errors.New("Invalid ipv6 local address provided as hostport string.")
}

return hostport[:colonIndex], nil
}

// COPIED FROM STD LIB TO USE WITH PROXY-AUTH HEADER
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
Expand Down
32 changes: 32 additions & 0 deletions connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,35 @@ func TestSampleProxyViaConnect(t *testing.T) {
incoming.CloseClient()
<-cleanedUp
}

func TestParsingAddrFromHostport(t *testing.T) {
_, err := parseAddrFromHostport("")
if err == nil {
t.Fatal("Expected an error.")
}

_, err = parseAddrFromHostport("1.1.1.1")
if err == nil {
t.Fatal("Expected an error.")
}

_, err = parseAddrFromHostport("[2001:db8::1]")
if err == nil {
t.Fatal("Expected an error.")
}

_, err = parseAddrFromHostport("somerandomstring.com")
if err == nil {
t.Fatal("Expected an error.")
}

ipv4Addr, _ := parseAddrFromHostport("1.1.1.1:8000")
if ipv4Addr != "1.1.1.1" {
t.Fatalf("Expected 1.1.1.1 but found %s", ipv4Addr)
}

ipv6Addr, _ := parseAddrFromHostport("[2001:db8::1]:80")
if ipv6Addr != "[2001:db8::1]" {
t.Fatalf("Expected [2001:db8::1] but found %s", ipv6Addr)
}
}

0 comments on commit 5fb86aa

Please sign in to comment.