为什么getservbyname没有返回正确的端口号?

时间:2014-09-20 02:17:16

标签: c++ windows sockets

在我的C:\ Windows \ System32 \ drivers \ etc \ service文件中,我看到了

echo 7 / tcp echo 7 / udp

所以我写了一个程序来测试getservbyname

#include <stdio.h>
#include <winsock2.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")  // winsock library

using namespace std;

int main(int argc, char *argv[]) 
{
WSADATA wsa;
SOCKET s;
sockaddr_in server;
servent     *serverInfo;


cout << "Initializing Winsock...." << endl;

if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
    cout << "Failed. Error code: " << WSAGetLastError();
    return 1;
}
cout << "initialized." << endl; 

serverInfo = getservbyname("echo", "tcp");
cout << "service echo:: s_name is " << serverInfo->s_name << endl; 
cout << "service echo:: s_aliases is " << serverInfo->s_aliases << endl; 
cout << "service echo:: s_port is " << serverInfo->s_port << endl; 
cout << "service echo:: s_proto is " << serverInfo->s_proto << endl; 

return 0;
}

当我运行它时,显示的结果如下:

Initializing Winsock....
initialized.
service echo:: s_name is echo
service echo:: s_aliases is 00724F08
service echo:: s_port is 1792
service echo:: s_proto is tcp

我的问题是为什么s_port是1792而不是7?我在文件服务中找不到1792。 有人可以解释一下吗?非常感谢。

1 个答案:

答案 0 :(得分:6)

7 * 256 = 1792

它是网络字节顺序。请尝试打印ntohs(serverInfo-&gt; s_port)。

如果您打算使用它来构建sockaddr_in,您可以直接将其复制到sin_port,因为这也是网络字节顺序。