Quantcast
Channel: Debian User Forums
Viewing all articles
Browse latest Browse all 3567

Programming • [Software] getservbyname panics if portname not present in /etc/services

$
0
0
Hello,

The fault is generated by the expression serv->s_port in the function call to ntohs(), due to the null pointer.

The code may be (in C++):

Code:

#include <iostream>using namespace std;#include <stdio.h>#include <stdlib.h>#include <netdb.h>int main(int argc, char* argv[]) { #define WKPN_VPA 5164 const char * serviceName  = "vpa"; const char * protocolName = "tcp"; int iVpaPort = 0; /* if the requested port number is not present in /etc/services,  * an exception occurs. It should just return a null pointer.  */ try {        struct servent *serv = getservbyname(serviceName, protocolName);        if( serv == NULL ){                 throw(std::runtime_error("getservbyname error!"));}        iVpaPort = ntohs(serv->s_port); } catch (const std::exception &e) {        cerr << "Requested port not present in /etc/services" << endl;        iVpaPort = WKPN_VPA;        return(EXIT_FAILURE); } return(EXIT_SUCCESS);}
Then, you can compile it with the following command:

Code:

g++ getservbyname.cpp -g -o getservbyname
When the getservbyname() fuction returns NULL, the exception is thrown.

Hope this helps. Please let me know.

--
notes:
1) please, use code tags to include commands and/or their logs in the body of a message.
2) moved to "Programming" sub-forum.

Statistics: Posted by Aki — 2024-07-29 13:48 — Replies 1 — Views 32



Viewing all articles
Browse latest Browse all 3567

Trending Articles