Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does golang provide htonl/htons?

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?

like image 312
Nan Xiao Avatar asked Sep 25 '13 03:09

Nan Xiao


People also ask

Are Htonl and Ntohl the same?

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.

Why Htons () is used in socket programming?

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.

What is the purpose of using Htonl and Htons functions in network programming using C ++?

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.

What is Ntohl?

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.


2 Answers

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).

like image 79
James Henstridge Avatar answered Oct 22 '22 17:10

James Henstridge


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.

like image 42
Intermernet Avatar answered Oct 22 '22 17:10

Intermernet