Use c-ares for DNS domain name resolution

1. c-ares is a non-blocking asynchronous DNS resolution implemented in C language . Libcurl, libevent, gevent, nodejs wireshark all use c-ares. Therefore, in general development of some service client clients, when connecting to the server server, you need What it does is domain name resolution.

2. Source code download path:  https://c-ares.haxx.se/download/

3. Compile and use

    (1) Win32 environment

      After downloading and decompressing the source code, enter the vs folder and open the project with tools such as VS2013 to compile Win32 caresd.lib and caresd.dll

static int CloudServerHostIsIP(const char * serverhost)
{
	struct in_addr addr;
	int lsuccess;
	lsuccess= inet_pton(AF_INET, serverhost, &addr);
	return lsuccess> 0 ? 0 : -1;
}

static void DNSCallBack(void* arg, int status, int timeouts, struct hostent* host)
{
	char **lpSrc;
	char  * lpHost = (char *)arg;

	if (status == ARES_SUCCESS)
	{
		for (lpSrc = host->h_addr_list; *lpSrc; lpSrc++)
		{
			char addr_buf[32] = "";
			ares_inet_ntop(host->h_addrtype, *lpSrc, addr_buf, sizeof(addr_buf));
			if (strlen(addr_buf) != 0)
			{
				strcpy(lpHost, addr_buf);
				break;
			}
		}
	}
}

static int DomainNameReSolution(const char * lpDomainName, char * lpHost)
{

	int lsuccess= 0;

	ares_channel channel;
	lsuccess= ares_library_init(ARES_LIB_INIT_ALL);
	if ((lsuccess= ares_init(&channel)) != ARES_SUCCESS) return -1;

	int trytime = 3;
	do{
		fd_set readers, writers;
		timeval tv;
		tv.tv_sec = 5;
		tv.tv_usec = 0;
		FD_ZERO(&readers);
		FD_ZERO(&writers);
		ares_gethostbyname(channel, lpDomainName, AF_INET, DNSCallBack, (char *)lpHost);
		int nfds = ares_fds(channel, &readers, &writers);
		if (nfds == 0){
			continue;
		}
		int count = select(nfds, &readers, NULL, NULL, &tv);
		if (count > 0){
			ares_process(channel, &readers, &writers);
			lsuccess= 0;
			break;
		}
		else{
			lsuccess= -1;
		}
	} while (trytime-- > 0);

	ares_destroy(channel);
	ares_library_cleanup();
	return lsuccess;
}

 

Guess you like

Origin blog.csdn.net/Swallow_he/article/details/89383598