Byte Order Conversion

Byte Order Conversion


Different kinds of computers use different conventions for the ordering of bytes within a
word. Some computers put the most significant byte within a word first (this is called
“big-endian” order), and others put it last (“little-endian” order).

So that machines with different byte order conventions can communicate, the Internet
protocols specify a canonical byte order convention for data transmitted over the network.
This is known as network byte order.
When establishing an Internet socket connection, you must make sure that the data
in the sin_port and sin_addr members of the sockaddr_in structure are represented in
network byte order. If you are encoding integer data in the messages sent through the socket,
you should convert this to network byte order too. If you don’t do this, your program may
fail when running on or talking to other kinds of machines.
If you use getservbyname and gethostbyname or inet_addr to get the port number
and host address, the values are already in network byte order, and you can copy them
directly into the sockaddr_in structure.
Otherwise, you have to convert the values explicitly. Use htons and ntohs to convert
values for the sin_port member. Use htonl and ntohl to convert IPv4 addresses for
the sin_addr member. (Remember, struct in_addr is equivalent to uint32_t.) These
functions are declared in ‘netinet/in.h’.
uint16_t htons (uint16 t hostshort) [Function]
This function converts the uint16_t integer hostshort from host byte order to network
byte order.
uint16_t ntohs (uint16 t netshort) [Function]
This function converts the uint16_t integer netshort from network byte order to host
byte order.
uint32_t htonl (uint32 t hostlong) [Function]
This function converts the uint32_t integer hostlong from host byte order to network
byte order.
This is used for IPv4 Internet addresses.
uint32_t ntohl (uint32 t netlong) [Function]
This function converts the uint32_t integer netlong from network byte order to host
byte order.
This is used for IPv4 Internet addresses.

转载于:https://www.cnblogs.com/haimingwey/archive/2012/04/28/2474697.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值