C++通過域名獲取IP地址的方法;調試通過!

// project.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
//#include <afx.h>
//#include <Winsock.h>
#include <winsock2.h>
#include <windows.h>
#pragma  comment(lib,"ws2_32.lib")

using namespace std;

bool  GetIpByDomainName(char *szHost, char szIp[100][100], int *nCount);

int _tmain(int argc, _TCHAR* argv[])
{

	int            nCount = 0;
	char        szIp0[100][100];
	char        szDomain[256] = { 0 };
	char        szIp[2048] = { 0 };
	strcpy_s(szDomain, "www.baidu.com");
	GetIpByDomainName(szDomain, szIp0, &nCount);
	int nK = 0;
	for (nK = 0; nK < nCount; nK++)
	{
		strcat_s(szIp, szIp0[nK]);
		strcat_s(szIp, "\r\n");
	}
	//OutputDebugString(szIp);
	return 0;
}


bool  GetIpByDomainName(char *szHost, char szIp[100][100], int *nCount)
{
	WSADATA        wsaData;
	char           szHostname[100];
	HOSTENT   *pHostEnt;
	int             nAdapter = 0;
	struct       sockaddr_in   sAddr;
	if (WSAStartup(0x0101, &wsaData))
	{
		//AfxMessageBox("WSAStartup   failed   %s/n", WSAGetLastError());
		return FALSE;
	}

	pHostEnt = gethostbyname(szHost);
	//pHostEnt = getaddrinfo(szHost);
	if (pHostEnt)
	{
		while (pHostEnt->h_addr_list[nAdapter])
		{
			memcpy(&sAddr.sin_addr.s_addr, pHostEnt->h_addr_list[nAdapter], pHostEnt->h_length);
			char  szBuffer[1024] = { 0 };

			sprintf_s(szBuffer, "%s", inet_ntoa(sAddr.sin_addr));

			strcpy_s(szIp[nAdapter], szBuffer);
			//OutputDebugString(szBuffer);
			nAdapter++;
		}

		*nCount = nAdapter;
	}
	else
	{
		DWORD  dwError = GetLastError();
		//CString  csError;
		//csError.Format("%d", dwError);
		//OutputDebugString(csError);
		//OutputDebugString("gethostbyname failed");
		*nCount = 0;
	}
	WSACleanup();
	return TRUE;

}

 

調試通過

 

還可參考 獲取本地ip方法:

https://blog.csdn.net/jite777/article/details/51890782/

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章