Skip to content

Commit

Permalink
Merge pull request #1322 from shirou/feature/net_fix_big_endian
Browse files Browse the repository at this point in the history
fix(net,linux): fix decodeaddress if Big Endian
  • Loading branch information
shirou committed Jul 9, 2022
2 parents 7a094df + f11e3ba commit cb1120d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 10 deletions.
10 changes: 10 additions & 0 deletions 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
}
8 changes: 6 additions & 2 deletions net/net_linux.go
Expand Up @@ -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 {
Expand Down
27 changes: 19 additions & 8 deletions net/net_linux_test.go
Expand Up @@ -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,
},
Expand All @@ -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
Expand Down

0 comments on commit cb1120d

Please sign in to comment.