简体   繁体   中英

Why does "inet_pton" return 0 when I'm using localhost?

I'm working on a socket interface where an application is trying to connect to another, this is my socket initialisation:

const char* pszLocalHost = "localhost";

int intSocket = socket(AF_INET, SOCK_STREAM, 0);

if ( intSocket == 0 ) {
    clsDebugService::exitWhenDebugQueueEmpty("Failed to create socket!");
}    
struct hostent* pHostEntry = gethostbyname(pszLocalHost);

if ( pHostEntry == nullptr ) {
    clsDebugService::exitWhenDebugQueueEmpty("Unable to resolve ip address!");
}
//Initliase and get address of localhost
struct sockaddr_in srvAddr;
bzero((char*)&srvAddr, sizeof(srvAddr));
//Set-up server address    
memcpy(&srvAddr.sin_addr, pHostEntry->h_addr_list[0], pHostEntry->h_length);
srvAddr.sin_family = AF_INET;
srvAddr.sin_port = htons(clsSocketThread::mscuint16Port);
char* pszIP =  inet_ntoa(srvAddr.sin_addr);

if ( pszIP != nullptr ) {
    qdbg() << "Setting up socket on ip: " << pszIP 
           << ", port: " << clsSocketThread::mscuint16Port
           << ((strPurpose.isEmpty() == true) ? "" : strPurpose);
}
socklen_t tSvrAddr = sizeof(srvAddr);
int intRC;
if ( blnIsModule == true ) {
    if ( inet_pton(AF_INET, pszLocalHost, &srvAddr.sin_addr) <= 0 ) {
        clsDebugService::exitWhenDebugQueueEmpty("Invalid address not supported!");
    }
    intRC = ::connect(intSocket, (const struct sockaddr*)&srvAddr, tSvrAddr);
}

Using the debugger I have traced an issue to the call to inet_pton, it returns 0, which according to: https://man7.org/linux/man-pages/man3/inet_pton.3.html

Means: 0 is returned if src does not contain a character string representing a valid network address in the specified address family.

Question is why ?

That same manual clearly states that the first argument must either be an IPv4 address of the form "ddd.ddd.ddd.ddd" or an IPv6 one. Since "localhost" is neither of those, the call fails. Using "127.0.0.1" should work though.

Here's the quote regarding IPv4 from the manual:

This function converts the character string src into a network address structure in the af address family, then copies the network address structure to dst. The af argument must be either AF_INET or AF_INET6. dst is written in network byte order.

The following address families are currently supported:

AF_INET src points to a character string containing an IPv4 network address in dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number of up to three digits in the range 0 to 255. The address is converted to a struct in_addr and copied to dst, which must be sizeof(struct in_addr) (4) bytes (32 bits) long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM