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?
I hope that no such architecture exists, but it could implement the sockets API thanks to the fact that htonl and ntohl are separate functions.
The htons() function translates a short integer from host byte order to network byte order. The unsigned short integer to be put into network byte order.
The htonl() and htons() functions shall return the argument value converted from host to network byte order. The ntohl() and ntohs() functions shall return the argument value converted from network to host byte order.
The ntohl() function translates a long integer from network byte order to host byte order. Parameter Description a. The unsigned long integer to be put into host byte order. in_addr_t netlong. Is typed to the unsigned long integer to be put into host byte order.
Network byte order is just big endian, so you can use the encoding/binary
package to perform the encoding.
For example:
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With