Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network byte order conversion with "char"

I've always been taught that if an integer is larger than a char, you must solve the byte ordering problem. Usually, I'll just wrap it in the hton[l|s] and convert it back with ntoh[l|s]. But I'm confused why this doesn't apply to single byte characters.

I'm sick of wondering why this is, and would love for a seasoned networks programmer to help me shed some light on why byte orderings only apply for multibyte integers.

Ref: https://beej.us/guide/bgnet/html/multi/htonsman.html

like image 934
Rev316 Avatar asked Mar 01 '10 17:03

Rev316


People also ask

How do you convert values between host and network byte order?

The htonl() function converts the unsigned integer hostlong from host byte order to network byte order. The htons() function converts the unsigned short integer hostshort from host byte order to network byte order. The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.

Is network order big-endian or little-endian?

The TCP/IP standard network byte order is big-endian. In order to participate in a TCP/IP network, little-endian systems usually bear the burden of conversion to network byte order.

What function would you use to convert a long to a network byte order?

Your port will simply be a number stored in an integer, and as such it must be converted into the proper form. The htons() function does just that. It takes one parameter and returns it in the expected network-byte order.

What are the purposes of the Ntohs () Htons () Nothl () and Htonl () functions in a socket program?

htons(), htonl(), ntohs(), ntohl() Since Intel is a "little-endian" machine, it's far more politically correct to call our preferred byte ordering "Network Byte Order". So these functions convert from your native byte order to network byte order and back again.


2 Answers

What you are looking for is endianness.

A big-endian architecture stores the bytes of a multibyte data type like so:

big-endian

while a little-endian architecture stores them in reverse:

little-endian

When data is transferred from one machine to another, the bytes of a single data type must be reordered to correspond with the endianness of the destination machine.

But when a data type only consists of one byte, there is nothing to reorder.

like image 57
Michael Myers Avatar answered Sep 21 '22 19:09

Michael Myers


Your networking stack will handle the bits inside the bytes correctly, you must only concern yourself with getting the bytes in the right order.

like image 44
Segfault Avatar answered Sep 19 '22 19:09

Segfault