Reputation: 17477
In C programming, when I want to send an integer across network, we need to use htonl() or htons() to convert the integer from host byte order to network byte order before sending it.
But in golang, I have checked the net package, and can't find the similar functions like htons/htonl. So how should I send an integer when using golang? Do I need to implement htons/htonl myself?
Upvotes: 27
Views: 13892
Reputation: 750
Just convert integers between big-endian and little-endian.
// NetToHostShort converts a 16-bit integer from network to host byte order, aka "ntohs"
func NetToHostShort(i uint16) uint16 {
data := make([]byte, 2)
binary.BigEndian.PutUint16(data, i)
return binary.LittleEndian.Uint16(data)
}
// NetToHostLong converts a 32-bit integer from network to host byte order, aka "ntohl"
func NetToHostLong(i uint32) uint32 {
data := make([]byte, 4)
binary.BigEndian.PutUint32(data, i)
return binary.LittleEndian.Uint32(data)
}
// HostToNetShort converts a 16-bit integer from host to network byte order, aka "htons"
func HostToNetShort(i uint16) uint16 {
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, i)
return binary.BigEndian.Uint16(b)
}
// HostToNetLong converts a 32-bit integer from host to network byte order, aka "htonl"
func HostToNetLong(i uint32) uint32 {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, i)
return binary.BigEndian.Uint32(b)
}
Upvotes: 0
Reputation: 43949
Network byte order is just big endian, so you can use the encoding/binary
package to perform the encoding.
data := make([]byte, 6)
binary.BigEndian.PutUint16(data, 0x1011)
binary.BigEndian.PutUint32(data[2:6], 0x12131415)
Alternatively, if you are writing to an io.Writer
, the binary.Write()
function from the same package may be more convenient (again, using the binary.BigEndian
value as the order
argument).
Upvotes: 29
Reputation: 19408
I think what you're after is ByteOrder
in encoding/binary
.
A ByteOrder specifies how to convert byte sequences into 16-, 32-, or 64-bit unsigned integers.
Upvotes: 4