精通
英语
和
开源
,
擅长
开发
与
培训
,
胸怀四海
第一信赖
锐英源精品开源心得,转载请注明:“锐英源www.wisestudy.cn,孙老师作品,电话13803810136。需要全文内容也请联系孙老师。
There’s been too much talk about this Network to Host Byte Orderconversion–now is the time for action! 过多谈论这个网络到主机字节顺序转换,现在是采取行动的时候了!
All righty. There are two types that you can convert: short (two bytes) and long (four bytes). These functions work for the unsigned variations as well. Say you want to convert a short from Host Byte Order to Network Byte Order. Start with "h" for "host", follow it with "to", then "n" for "network", and "s" for "short": h-to-n-s, or htons() (read: "Host to Network Short").
有两种类型,您可以转换:short(两个字节)和long(4个字节)。这些函数也适合无符号变量。假设你想从主机字节顺序很快的转换为网络字节顺序。开始以”h“为“主机”,接着”to“,然后为“h”为“网络”和“s”为“短”:h-to-n-s或htons()(读作:“主机到网络”)。
It’s almost too easy... 几乎太简单了…
You can use every combination if "n", "h", "s", and "l" you want, not counting the really stupid ones. For example, there is NOT a stolh() ("Short to Long Host") function–not at this party, anyway. But there are:
您可以使用你想要的“n”,“h”,“s”,和“l”的任何一个组合,不算傻瓜式的。例如,在这里面没有一个stolh()(短到长主机)的函数功能,无论如何。就这些:
• htons() – "Host to Network Short" •htons()——“主机网络短”
• htonl() – "Host to Network Long" •htonl()——“主机网络长”
• ntohs() – "Network to Host Short" •ntohs()——“网络主机短”
• ntohl() – "Network to Host Long" •ntohl()——“网络主机长”
Now, you may think you’re wising up to this. You might think, "What do I do if I have to change byte order on a char?" Then you might think, "Uh, never mind." You might also think that since your 68000 machine already uses network byte order, you don’t have to call htonl() on your IP addresses. You would be right, BUT if you try to port to a machine that has reverse network byte order, your program will fail. Be portable! This is a Unix world! (As much as Bill Gates would like to think otherwise.) Remember: put your bytes in Network Byte Order before you put them on the network.
现在,你可能意识到了这一点。你可能会想,“如果我必须在一个char类型中改变字节顺序该怎么办?“然后你可能会想,“哦,不要紧。“您可能还认为既然你的机器68000已经使用网络字节顺序,,你不必在你的IP地址中调用htonl()。你是正确的,但如果你试图移植到另外一个已经转换过的网络字节顺序的机器上,您的程序将会失败。这是一个Unix的时代!(除非比尔盖茨也这样认为,否则。)记住:在你把字节放到网络上之前把他们放到网络字节顺序。
A final point: why do sin_addr and sin_port need to be in Network Byte Order in a struct sockaddr_in, but sin_family does not? The answer: sin_addr and sin_port get encapsulated in the packet at the IP and UDP layers, respectively. Thus, they must be in Network Byte Order. However, the sin_family field is only used by the kernel to determine what type of address the structure contains, so it must be in Host Byte Order. Also, since sin_family does not get sent out on the network, it can be in Host Byte Order.
最后一点:为什么sin_addr和sin_port在sockaddr_in结构中需要在网络字节顺序,但sin_family不用?答案是:sin_addr sin_port在包UDP层中得到IP和封装,因此,他们必须在网络字节顺序。然而,sin_family字段只是使用由内核决定什么类型的地址包含结构,因此它必须在主机字节顺序。而且,由于sin_family在网络中没有发送出去,它可以在主机字节顺序。