Getaddrinfo with error: Servname is not supported for ai_socktype in C ++

This, I noticed, is due to the port. port is a C ++ string. When I hardcode the port number, say "4091", I do not see this problem. Any suggestions?

int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; 
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; 

cout << "port: " << port << endl;

const char * por = port.c_str();

if ((rv = getaddrinfo(NULL, por, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
}
+3
source share
1 answer

It may seem completely dumb, but that’s how I fixed it.

    int pp = atoi(port.c_str());
    char buffer[50];
    sprintf( buffer, "%d", pp );   

    if ((rv = getaddrinfo(NULL, buffer, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    }

EDIT: The actual problem was that I was reading port information from a file. when i use getline () it did not delete the new char line at the end for any reason. The above fix (if you call it a fix) is no longer required.

+5
source

All Articles