|
|
@ -5,6 +5,10 @@ import ( |
|
|
|
"net" |
|
|
|
) |
|
|
|
|
|
|
|
const ( |
|
|
|
DEFAULT_PORT = 8001 |
|
|
|
) |
|
|
|
|
|
|
|
/* Listener */ |
|
|
|
|
|
|
|
type Listener interface { |
|
|
@ -26,12 +30,12 @@ const ( |
|
|
|
DEFAULT_BUFFERED_CONNECTIONS = 10 |
|
|
|
) |
|
|
|
|
|
|
|
func NewListener(protocol string, laddr string) Listener { |
|
|
|
ln, err := net.Listen(protocol, laddr) |
|
|
|
func NewDefaultListener(protocol string, listenAddr string) Listener { |
|
|
|
listener, err := net.Listen(protocol, listenAddr) |
|
|
|
if err != nil { panic(err) } |
|
|
|
|
|
|
|
dl := &DefaultListener{ |
|
|
|
listener: ln, |
|
|
|
listener: listener, |
|
|
|
connections: make(chan *Connection, DEFAULT_BUFFERED_CONNECTIONS), |
|
|
|
} |
|
|
|
|
|
|
@ -66,7 +70,7 @@ func (l *DefaultListener) Connections() <-chan *Connection { |
|
|
|
} |
|
|
|
|
|
|
|
func (l *DefaultListener) LocalAddress() *NetAddress { |
|
|
|
return NewNetAddress(l.listener.Addr()) |
|
|
|
return GetLocalAddress() |
|
|
|
} |
|
|
|
|
|
|
|
func (l *DefaultListener) Stop() { |
|
|
@ -74,3 +78,48 @@ func (l *DefaultListener) Stop() { |
|
|
|
l.listener.Close() |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
/* local address helpers */ |
|
|
|
|
|
|
|
func GetLocalAddress() *NetAddress { |
|
|
|
laddr := GetUPNPLocalAddress() |
|
|
|
if laddr != nil { return laddr } |
|
|
|
|
|
|
|
laddr = GetDefaultLocalAddress() |
|
|
|
if laddr != nil { return laddr } |
|
|
|
|
|
|
|
panic("Could not determine local address") |
|
|
|
} |
|
|
|
|
|
|
|
// UPNP external address discovery & port mapping
|
|
|
|
// TODO: more flexible internal & external ports
|
|
|
|
func GetUPNPLocalAddress() *NetAddress { |
|
|
|
nat, err := Discover() |
|
|
|
if err != nil { return nil } |
|
|
|
|
|
|
|
ext, err := nat.GetExternalAddress() |
|
|
|
if err != nil { return nil } |
|
|
|
|
|
|
|
_, err := nat.AddPortMapping("tcp", DEFAULT_PORT, DEFAULT_PORT, "tendermint", 0) |
|
|
|
if err != nil { return nil } |
|
|
|
|
|
|
|
return NewNetAddressIPPort(ext, DEFAULT_PORT) |
|
|
|
} |
|
|
|
|
|
|
|
// Naive local IPv4 interface address detection
|
|
|
|
// TODO: use syscalls to get actual ourIP. http://pastebin.com/9exZG4rh
|
|
|
|
func GetDefaultLocalAddress() *NetAddress { |
|
|
|
addrs, err := net.InterfaceAddrs() |
|
|
|
if err != nil { panic("Wtf") } |
|
|
|
for _, a := range addrs { |
|
|
|
ipnet, ok := a.(*net.IPNet) |
|
|
|
if !ok { continue } |
|
|
|
v4 := ipnet.IP.To4() |
|
|
|
if v4 == nil || v4[0] == 127 { continue } // loopback
|
|
|
|
return NewNetAddress(a) |
|
|
|
} |
|
|
|
return nil |
|
|
|
} |
|
|
|
|
|
|
|
|