htons中的混乱

编程入门 行业动态 更新时间:2024-10-28 13:27:48
本文介绍了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 字节的整数,你必须首先将它转换为网络使用 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.)

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

本文发布于:2023-07-29 19:40:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1243484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:混乱   htons

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!