Commit 9f514399 authored by AlexStocks's avatar AlexStocks

Add: IsSameAddr and its unit test

parent afd79590
......@@ -122,3 +122,26 @@ func isValidNetworkInterface(face net.Interface) bool {
return true
}
// refer from https://github.com/facebookarchive/grace/blob/master/gracenet/net.go#L180
func IsSameAddr(addr1, addr2 net.Addr) bool {
if addr1.Network() != addr2.Network() {
return false
}
addr1s := addr1.String()
addr2s := addr2.String()
if addr1s == addr2s {
return true
}
// This allows for ipv6 vs ipv4 local addresses to compare as equal. This
// scenario is common when listening on localhost.
const ipv6prefix = "[::]"
addr1s = strings.TrimPrefix(addr1s, ipv6prefix)
addr2s = strings.TrimPrefix(addr2s, ipv6prefix)
const ipv4prefix = "0.0.0.0"
addr1s = strings.TrimPrefix(addr1s, ipv4prefix)
addr2s = strings.TrimPrefix(addr2s, ipv4prefix)
return addr1s == addr2s
}
......@@ -18,6 +18,7 @@
package gxnet
import (
"net"
"testing"
)
......@@ -30,3 +31,26 @@ func TestGetLocalIP(t *testing.T) {
assert.NoError(t, err)
t.Log(ip)
}
func TestIsSameAddr(t *testing.T) {
addr1 := net.TCPAddr{
IP: []byte("192.168.0.1"),
Port: 80,
Zone: "cn/shanghai",
}
addr2 := net.TCPAddr{
IP: []byte("192.168.0.2"),
Port: 80,
Zone: "cn/shanghai",
}
assert.True(t, IsSameAddr(&addr1, &addr1))
assert.False(t, IsSameAddr(&addr1, &addr2))
addr1.IP = []byte("2001:4860:0:2001::68")
addr1.Zone = ""
addr2.IP = []byte("2001:4860:0000:2001:0000:0000:0000:0068")
addr2.Zone = ""
assert.True(t, IsSameAddr(&addr1, &addr1))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment