// 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/