diff --git a/internal/common/endian.go b/internal/common/endian.go new file mode 100644 index 000000000..147cfdc4b --- /dev/null +++ b/internal/common/endian.go @@ -0,0 +1,10 @@ +package common + +import "unsafe" + +// IsLittleEndian checks if the current platform uses little-endian. +// copied from https://github.com/ntrrg/ntgo/blob/v0.8.0/runtime/infrastructure.go#L16 (MIT License) +func IsLittleEndian() bool { + var x int16 = 0x0011 + return *(*byte)(unsafe.Pointer(&x)) == 0x11 +} diff --git a/net/net_linux.go b/net/net_linux.go index 81cde8133..c08997196 100644 --- a/net/net_linux.go +++ b/net/net_linux.go @@ -721,9 +721,13 @@ func decodeAddressWithContext(ctx context.Context, family uint32, src string) (A return Addr{}, fmt.Errorf("decode error, %w", err) } var ip net.IP - // Assumes this is little_endian + if family == syscall.AF_INET { - ip = net.IP(ReverseWithContext(ctx, decoded)) + if common.IsLittleEndian() { + ip = net.IP(ReverseWithContext(ctx, decoded)) + } else { + ip = net.IP(decoded) + } } else { // IPv6 ip, err = parseIPv6HexStringWithContext(ctx, decoded) if err != nil { diff --git a/net/net_linux_test.go b/net/net_linux_test.go index bec091c54..d5d6252a8 100644 --- a/net/net_linux_test.go +++ b/net/net_linux_test.go @@ -137,14 +137,6 @@ func TestDecodeAddress(t *testing.T) { assert := assert.New(t) addr := map[string]AddrTest{ - "0500000A:0016": { - IP: "10.0.0.5", - Port: 22, - }, - "0100007F:D1C2": { - IP: "127.0.0.1", - Port: 53698, - }, "11111:0035": { Error: true, }, @@ -159,6 +151,25 @@ func TestDecodeAddress(t *testing.T) { Error: true, }, } + if common.IsLittleEndian() { + addr["0500000A:0016"] = AddrTest{ + IP: "10.0.0.5", + Port: 22, + } + addr["0100007F:D1C2"] = AddrTest{ + IP: "127.0.0.1", + Port: 53698, + } + } else { + addr["0A000005:0016"] = AddrTest{ + IP: "10.0.0.5", + Port: 22, + } + addr["7F000001:D1C2"] = AddrTest{ + IP: "127.0.0.1", + Port: 53698, + } + } for src, dst := range addr { family := syscall.AF_INET