Merge pull request #1322 from shirou/feature/net_fix_big_endian

fix(net,linux): fix decodeaddress if Big Endian
This commit is contained in:
shirou 2022-07-09 10:49:16 +09:00 committed by GitHub
commit cb1120d239
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 10 deletions

10
internal/common/endian.go Normal file
View File

@ -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
}

View File

@ -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 {

View File

@ -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