TIL about socket port byte order
I was writing a simple server in arm64 assembly and was trying to bind port 300 (spartan).
.hword 0x012c // htons(300)
The server would bind fine, but to an odd port like 11265. The issue was byte order (endianness?).
My “discoveries” are:
- Network byte order is big-endian
- ARM64 is little-endian
I was storing 0x012c as .hword on ARM64 The kernel reads bytes 2c 01 as big endian, interpreting it as 0x2c01 = 11265
The solurtion was to explicitly define the order:
.byte 0x01, 0x2c
The htons() function will handle it properly, but with assembly you have to do it manually.