Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ getservbyport returning wrong information

When I run this code:

#include <iostream>
#include <netdb.h>

int main(){
    struct servent* serv = getservbyport(22, "tcp");
    if(serv != NULL){
        std::cout<<"name: "<<serv->s_name<<" type: "<<serv->s_proto<<std::endl;
    }
    return 0;
}

The result is:

name: pcanywherestat type: tcp

If I were to run getservbyport(21, "tcp"); the variable serv would return NULL.
When I go to the the /etc/services file, it includes these lines:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ssh              22/udp     # SSH Remote Login Protocol
ssh              22/tcp     # SSH Remote Login Protocol

ftp              21/tcp     # File Transfer [Control]

If I search the file for pcanywherestat it doesn’t exist within the file. Why am I getting this result from running that code?

>Solution :

getservbyport(3) and family store numeric values in Big Endian (aka, network byte order). As a result, you need to convert any int’s, in this case with htons(), thusly:

struct servent* serv = getservbyport(htons(22), "tcp");

hton*(3) convert values between host and network byte order

Edit: the functions htons, htonl, htonll convert from host to short int, long int, and long long int, respectively.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading