简体   繁体   中英

why doesn't getservbyname return the correct port number?

in my C:\\Windows\\System32\\drivers\\etc\\service file, I saw

echo 7/tcp echo 7/udp

so I wrote a program to test 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;
}

When I ran it, below is the displayed result:

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

My question is why s_port is 1792 not 7? I couldn't find a 1792 in the file service. Can someone kindly explain? Thanks a lot.

7*256=1792

It's in network byte order. Try printing ntohs(serverInfo->s_port) instead.

If you were going to use it to build a sockaddr_in you could just copy it directly to the sin_port since that's network byte order too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM