JustWe
JustWe

Reputation: 4484

Is NetworkByteOrder is the same as Big endian?

I create a demo to prove network byte order is the same as big endian:

#include "stdio.h"
#include "stdint.h"
#include "winsock2.h"
#define BL32(x)  ((((x) & 0x000000ffUL) << 24) | \
                 (((x) & 0x0000ff00UL) <<  8) | \
                 (((x) & 0x00ff0000UL) >>  8) | \
                 (((x) & 0xff000000UL) >> 24))
int main(int argc, char* argv[])
{
    uint32_t s = INT_MAX; // little endian
    uint32_t network = htonl(s);
    uint32_t bigendian = BL32(s);
    if(network == bigendian) {
        printf("nbo is same as big endian\n");
    } else {
        printf("nbo isn't same as big endian\n");
    }

    return 0;
}

This program runs on an x86(litte endian) Windows PC, and it gives output:

nbo is same as big endian

I didn't see this mentioned in the textbook or tutorial, so I want to confirm it's right or not.

BTW I think it's very important to help understand what is byte order in the network. Why most of the question concentrates only on "big vs little endian"...

Upvotes: 0

Views: 576

Answers (1)

Barmar
Barmar

Reputation: 780871

Yes, it is. You can read it in the Wikipedia article on Endianness

Big-endian is the most common format in data networking; fields in the protocols of the Internet protocol suite, such as IPv4, IPv6, TCP, and UDP, are transmitted in big-endian order. For this reason, big-endian byte order is also referred to as network byte order.

You generally don't need to know whether network byte order is big- or little-endian. Just use the ntohX and htonX macros, and it will do the right thing. If you're on hardware that has the same byte order as the network protocols, it will leave the value alone; if you're on a machine with the opposite byte order, it will swap the bytes.

Upvotes: 2

Related Questions