Skip to content

Commit

Permalink
nat, node, example/chat: expose IsPrivateIP() function, and only set …
Browse files Browse the repository at this point in the history
…the nodes external address to the NAT Traversal-provided one should a `Host` not be configured
  • Loading branch information
iwasaki-kenta committed Feb 19, 2019
1 parent 7c4b1b7 commit 1b4ddbc
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 6 deletions.
5 changes: 4 additions & 1 deletion examples/chat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/perlin-network/noise/cipher/aead"
"github.com/perlin-network/noise/handshake/ecdh"
"github.com/perlin-network/noise/log"
"github.com/perlin-network/noise/nat"
"github.com/perlin-network/noise/payload"
"github.com/perlin-network/noise/protocol"
"github.com/perlin-network/noise/skademlia"
Expand Down Expand Up @@ -68,12 +69,14 @@ func setup(node *noise.Node) {
}

func main() {
hostFlag := flag.String("h", "127.0.0.1", "host to listen for peers on")
portFlag := flag.Uint("p", 3000, "port to listen for peers on")
flag.Parse()

params := noise.DefaultParams()
//params.NAT = nat.NewPMP()
params.NAT = nat.NewPMP()
params.Keys = skademlia.RandomKeys()
params.Host = *hostFlag
params.Port = uint16(*portFlag)

node, err := noise.NewNode(params)
Expand Down
6 changes: 3 additions & 3 deletions nat/mod.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ func parseCIDR(s string) *net.IPNet {
return block
}

// isPrivateIP returns whether or not an IP is within a private range.
func isPrivateIP(ip net.IP) bool {
// IsPrivateIP returns whether or not an IP is within a private range.
func IsPrivateIP(ip net.IP) bool {
for _, ipnet := range privateBlocks {
if ipnet.Contains(ip) {
return true
Expand Down Expand Up @@ -65,7 +65,7 @@ func activeGateways() ([]net.IP, error) {
continue
}

if isPrivateIP(address.IP) {
if IsPrivateIP(address.IP) {
if ip := address.IP.Mask(address.Mask).To4(); ip != nil {
ip[3] = ip[3] | 0x01
gateways = append(gateways, ip)
Expand Down
4 changes: 2 additions & 2 deletions node.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func (n *Node) Kill() {
}

func (n *Node) ExternalAddress() string {
if n.nat != nil {
if n.nat != nil && nat.IsPrivateIP(net.ParseIP(n.host)) {
externalIP, err := n.nat.ExternalIP()
if err != nil {
panic(err)
Expand All @@ -303,5 +303,5 @@ func (n *Node) ExternalAddress() string {
return fmt.Sprintf("%s:%d", externalIP.String(), n.externalPort)
}

return fmt.Sprintf("%s:%d", n.host, n.ExternalPort())
return fmt.Sprintf("%s:%d", n.host, n.externalPort)
}

0 comments on commit 1b4ddbc

Please sign in to comment.