From 5ae9cc6536a41337cc8272f3ea8a9bd6123a2742 Mon Sep 17 00:00:00 2001 From: Michael Davidsaver Date: Thu, 10 Jul 2025 20:10:17 -0700 Subject: [PATCH] gethostbyname -> getaddrinfo Prefer reentrant DNS API --- modules/libcom/src/osi/os/posix/osdSock.c | 57 ++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/modules/libcom/src/osi/os/posix/osdSock.c b/modules/libcom/src/osi/os/posix/osdSock.c index 0d873e628..41f6580f0 100644 --- a/modules/libcom/src/osi/os/posix/osdSock.c +++ b/modules/libcom/src/osi/os/posix/osdSock.c @@ -41,6 +41,13 @@ # define SOCK_CLOEXEC (0) #endif +#if defined(AI_PASSIVE) && !defined(__rtems__) +# define USE_INFO +#else +# define USE_BY +#endif + +#ifdef USE_BY /* * Protect some routines which are not thread-safe */ @@ -60,7 +67,7 @@ static void unlockInfo (void) { epicsMutexUnlock (infoMutex); } - +#endif static size_t nAttached; @@ -164,6 +171,7 @@ LIBCOM_API void epicsStdCall epicsSocketDestroy ( SOCKET s ) } } +#ifdef USE_BY /* * ipAddrToHostName * On many systems, gethostbyaddr must be protected by a @@ -214,6 +222,53 @@ LIBCOM_API int epicsStdCall hostToIPAddr unlockInfo (); return ret; } +#endif +#ifdef USE_INFO +unsigned epicsStdCall ipAddrToHostName(const struct in_addr *pAddr, char *pBuf, unsigned bufSize) +{ + osiSockAddr query; + if(!bufSize) + return 0; // non-sense + + memset(&query, 0, sizeof(query)); + query.ia.sin_family = AF_INET; + query.ia.sin_addr = *pAddr; + + int ret = getnameinfo(&query.sa, sizeof(query), pBuf, bufSize, NULL, 0, NI_NAMEREQD); + if(ret==0) { + ret = strlen (pBuf); + + } else { // lookup fails + ret = 0; // indicate failure to caller + } + return ret; +} + +int epicsStdCall hostToIPAddr(const char *pHostName, struct in_addr *pIPA) +{ + struct addrinfo hint, *result = NULL; + + memset(&hint, 0, sizeof(hint)); + hint.ai_family = AF_INET; + + int ret = getaddrinfo(pHostName, NULL, &hint, &result); + if(ret==0) { + const struct addrinfo *ai; + ret = -1; + for(ai = result; ai; ai = ai->ai_next) { + assert(ai->ai_family==AF_INET); // ensured by hint + const struct sockaddr_in *answer = (const struct sockaddr_in*)ai->ai_addr; + *pIPA = answer->sin_addr; + ret = 0; + break; + } + } + if(result) { + freeaddrinfo(result); + } + return ret; +} +#endif