网络编程端口设置问题

来源:百度知道 编辑:UC知道 时间:2024/06/28 03:38:36
#include "stdafx.h"
#include <stdio.h>
#include<winsock.h>
#pragma comment( lib, "ws2_32.lib" )
int _tmain(int argc, _TCHAR* argv[])
{
USHORT a=(USHORT)htonl(4512);
printf("%d",a);

return 0;
}
我想通过htonl()函数设置一个端口号 为什么设置出来的值都是0 也就是上面a的值

是这样的,htonl是host to network long 的缩写,意思是将本地的int类型的字节序转化为网络字节序,注意,是long int 类型,本地是little-endian,网络是big-endian。

在这里:

4512的二进制形式为: (高字节)00000000 00000000 00010000 00111000(低字节)
在调用htonl之后变为: (高字节)00111000 00010000 00000000 00000000(低字节)

而你又用一个(USHORT)将它强制转化为shoort int,这是就抛掉两个高字节于是 a 变成 00000000 00000000,你再按%d输出,自然是0了.

所以,改动很简单,将htonl改为htons就可以了.