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:
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.