0

I am writing server and client and i have some integers to pass.

In my server application i am recieving an integer from the client.

In the client do i call ntohl or htonl on the integer? If i call either one of these, when i recieve the integer do i have to call ntohl or htonl again? Or do i only call ntohl/htonl on the server side, but not the client side?

In other words, when/where and how many times do i use htonl or ntohl for each integer?

Also, do i have to do ntohl/htonl for strings/chars arrays? Does chars have to be converted?

4

3 回答 3

1

在客户端中,我是在整数上调用 ntohl 还是 htonl?

它与您是客户端还是服务器无关。这与您是发送还是接收有关。如果你正在发送,你想要网络字节顺序,所以你调用htonl()。如果您正在收货,则需要主机订单,因此您致电ntohl().

如果我调用其中任何一个,当我收到整数时,我是否必须再次调用 ntohl 或 htonl?

是的。发送者应该已经将数据按网络字节顺序排列;接收者必须为他的本地主机将其放入主机顺序中。

换句话说,我何时/何地以及多少次对每个整数使用 htonl 或 ntohl?

htonl()发送时;ntohl()接收时。

于 2013-05-19T10:04:12.980 回答
1

发送整数时,始终调用hton...()以确保字节从发送机器的本机字节顺序转换为网络字节顺序。

读取整数时,始终调用ntoh...()以确保字节从网络字节顺序转换为接收机器的本机字节顺序。

在本机字节顺序与网络字节顺序相同的机器上,这些功能被实现为无操作。在本地字节顺序不同的机器上,函数执行字节交换。

于 2013-05-18T02:24:11.223 回答
0

这种情况下的典型设置是调用htonl客户端(因为您想将整数放入网络,即协议顺序)和ntohl服务器(因为您想从网络转换回主机顺序)。

字符串没有等价物ntohl(尽管您必须安排客户端和服务器就所使用的字符编码达成一致,即让双方都使用 UTF-8)。

于 2013-05-18T02:22:26.483 回答