From a57c1ef8446f5d82fb096ed6cdc4d3bbb153941c Mon Sep 17 00:00:00 2001 From: louix <28579246+louix@users.noreply.github.com> Date: Thu, 6 Jun 2024 15:54:36 +0100 Subject: [PATCH] use getaddrinfo over gethostbyname --- libs/mysql/socket.c | 39 ++++++++++++++++++++++----------------- src/std/socket.c | 39 +++++++++++++++++++++------------------ 2 files changed, 43 insertions(+), 35 deletions(-) diff --git a/libs/mysql/socket.c b/libs/mysql/socket.c index 17daa7ac0..dfcefab76 100644 --- a/libs/mysql/socket.c +++ b/libs/mysql/socket.c @@ -117,25 +117,30 @@ int psock_recv( PSOCK s, char *buf, int size ) { return ret; } -PHOST phost_resolve( const char *host ) { - PHOST ip = inet_addr(host); - if( ip == INADDR_NONE ) { - struct hostent *h; -# if defined(OS_WINDOWS) || defined(OS_MAC) || defined(OS_CYGWIN) - h = gethostbyname(host); -# else - struct hostent hbase; - char buf[1024]; - int errcode; - gethostbyname_r(host,&hbase,buf,1024,&h,&errcode); -# endif - if( h == NULL ) - return UNRESOLVED_HOST; - ip = *((unsigned int*)h->h_addr_list[0]); - } - return ip; +PHOST phost_resolve(const char *host) { + struct addrinfo hints, *res; + PHOST ip = INADDR_NONE; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + + int status = getaddrinfo(host, NULL, &hints, &res); + if (status != 0) { + return UNRESOLVED_HOST; + } + + if (res != NULL) { + struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr; + ip = ipv4->sin_addr.s_addr; + } + + freeaddrinfo(res); + + return ip; } + SERR psock_connect( PSOCK s, PHOST host, int port ) { struct sockaddr_in addr; memset(&addr,0,sizeof(addr)); diff --git a/src/std/socket.c b/src/std/socket.c index f717dc9ae..0c551d561 100644 --- a/src/std/socket.c +++ b/src/std/socket.c @@ -193,27 +193,30 @@ HL_PRIM int hl_socket_recv_char( hl_socket *s ) { return (unsigned char)cc; } -HL_PRIM int hl_host_resolve( vbyte *host ) { - unsigned int ip; +HL_PRIM int hl_host_resolve(vbyte *host) { + struct addrinfo hints, *res; + unsigned int ip = INADDR_NONE; + hl_blocking(true); - ip = inet_addr((char*)host); - if( ip == INADDR_NONE ) { - struct hostent *h; -# if defined(HL_WIN) || defined(HL_MAC) || defined(HL_IOS) || defined(HL_TVOS) || defined (HL_CYGWIN) || defined(HL_CONSOLE) - h = gethostbyname((char*)host); -# else - struct hostent hbase; - char buf[1024]; - int errcode; - gethostbyname_r((char*)host,&hbase,buf,1024,&h,&errcode); -# endif - if( h == NULL ) { - hl_blocking(false); - return -1; - } - ip = *((unsigned int*)h->h_addr_list[0]); + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + + int status = getaddrinfo((char*)host, NULL, &hints, &res); + if (status != 0) { + hl_blocking(false); + return -1; + } + + if (res != NULL) { + struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr; + ip = ipv4->sin_addr.s_addr; } + + freeaddrinfo(res); hl_blocking(false); + return ip; }