FourOfAKind
FourOfAKind

Reputation: 2418

getaddrinfo failing with error : Servname not supported for ai_socktype in C++

This, I observed, because of the port. port is C++ string. When I hard code the port number say "4091" I dont see this issue. 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));
}

Upvotes: 4

Views: 22181

Answers (1)

FourOfAKind
FourOfAKind

Reputation: 2418

This might look absolute dumb but this is 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 issue was that I was reading the port information from a file. when I use the getline() it did not remove the newline char at the end for what ever reason. The above fix (if you call it a fix) no longer needed.

Upvotes: 8

Related Questions