当前位置: 技术问答>linux和unix
网络编程(tcp),对服务器端口的转换htons(server_port); 到底对不对?请帮忙看看
来源: 互联网 发布时间:2015-12-07
本文导语: 部分代码如下: server_port=8000; bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; server_addr.sin_addr.s_addr = inet_addr(host_name); server_addr.sin_port=htons(server_port); printf("nserver ip= %s ,port = %d", inet_ntoa(server_add...
部分代码如下:
server_port=8000;
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host_name);
server_addr.sin_port=htons(server_port);
printf("nserver ip= %s ,port = %d", inet_ntoa(server_addr.sin_addr),server_addr.sin_port);
------------
打印出的port = 16415;(怎么不是8000啊?IP是对的),往下执行connect()也就失败了。
|
可以这样填充sockaddr结构:
memset(&localaddr, 0, sizeof(localaddr));
if(! inet_aton(sListenIPAddr, &(localaddr.sin_addr)))
{
perror("inet_aton");
exit(0);
}
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(static_cast (nListenPort));
memset(&localaddr, 0, sizeof(localaddr));
if(! inet_aton(sListenIPAddr, &(localaddr.sin_addr)))
{
perror("inet_aton");
exit(0);
}
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(static_cast (nListenPort));
|
网络字节序和很多主机字节序不同,所以需要用htons或者htonl来更改字节序