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

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

问题描述

当我通过socket将一个整数变量从一个进程发送到另一个进程,然后在接收端打印该值,不使用ntohl/htonl,该值仍然相同,那么除了初始化我还需要在哪里使用这些函数套接字结构.我理解小/大端.但是为什么我们需要在值保持不变的情况下将端口和 IP 号转换为主机/网络字节顺序.请详细说明整数是如何通过网络传输的?

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 字节的整数,你必须首先将它转换为网络使用 htonshtonl 的字节顺序,接收计算机必须使用 ntohsntohl 将其转换为主机字节顺序.

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

但是,如果您希望您的程序具有可移植性,则不能始终如此.比如有一天,发送计算机可能是 Intel 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天全站免登陆