混乱htons-小端/大端 [英] Confusion in htons- little endian/ big endian

查看:257
本文介绍了混乱htons-小端/大端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过socket发送一个整数变量从一个程序到其他,然后在收到最终打印值,该值仍然是相同的,而无需使用ntohl / htonl,然后我在哪里需要使用不是初始化等这些功能插座的结构。我明白豆蔻/大端。但是为什么我们需要转换端口和IP号到主机/网络字节顺序时,值将保持不变。请详细说明整数如何tranferred通过网络?

When I send a integer variable from one process to other through socket, and then printing the value at received end, the value is still the same without using ntohl/htonl, then where do I need to use these functions other than initializing socket structures. I understand litte/big endian. But why do we need to convert port and IP nos to host/network byte order when value remains the same. Please explain in detail how the integer is tranferred over network?

推荐答案

如果你希望你的程序可以移植,那么任何时候你的规模通过网络发送一个大于1的整数字节,则必须先将其转换为网络使用 htons htonl ,并接收计算机必须转换用它来主机字节顺序 ntohs和或 ntohl

If you want your program to be portable, then any time you send an integer greater than 1 byte in size over the network, you must first convert it to network byte order using htons or htonl, and the receiving computer must convert it to host byte order using ntohs or ntohl.

在你的情况下,值还是一样的原因可能是因为发送计算机与接收计算机是相同的字节序。换句话说,发送计算机,你正在使用的接收计算机都是小端(或大端,无论情况而定)。

In your case, the reason the value is still the same is probably because the sending computer and the receiving computer are of the same endianness. In other words, the sending computer and the receiving computer you're working with are both little endian (or big endian, whatever the case may be.)

但如果你想你的程序是便携式的,你不能靠这个来始终如此。有一天,例如,发送计算机可能是英特尔的x86,而接收可能是在Sun SPARC,然后如果你不使用你的程序将无法 htons

But if you want your program to be portable, you can't rely on this to always be the case. One day, for example, the sending computer may be an Intel x86, and the receiving may be a Sun SPARC, and then your program will fail if you don't use htons.

这篇关于混乱htons-小端/大端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆