gethostbyname取ip地址, gethostbyaddr取域名
#include <iostream>
// #ifndef WIN32_LEAN_AND_MEAN
// #define WIN32_LEAN_AND_MEAN
// #endif
#include <winsock2.h>
#include <windows.h>
#include <conio.h>
#pragma comment(lib,"ws2_32.lib")
using std::cout;
using std::endl;
using std::cerr;
int main(int argc,char *argv[],char *envp[])
{
int iretcode = 0;
const char *pip_addr = "www.baidu.com";//or "220.181.38.148";//
WSADATA wsa = {0};
iretcode = WSAStartup(MAKEWORD(2,2),&wsa);
if(iretcode != 0)
return iretcode;// WSAStartup function error.
///////////////////////////////////////////////
// get address dwip_addr of network byte order.
unsigned long dwip_addr = inet_addr(pip_addr);// to struct in_addr
if(dwip_addr == INADDR_NONE)
{
struct hostent *phentry = NULL;
phentry = gethostbyname(pip_addr);// to struct hostent
if(phentry != NULL)
dwip_addr = *( (unsigned long *)(phentry->h_addr_list[0]) );//take the first address of the domain name.
}
///////////////////////////////////////////////
cout<<std::hex<<"ip address (network byte order): "<<dwip_addr<<endl;
// get ip
cout<<"ip address: "<<inet_ntoa(*((struct in_addr *)&dwip_addr) )<<endl;// to char * address.
// get domain name
struct hostent *phe = gethostbyaddr((char *)&dwip_addr,sizeof(dwip_addr),AF_INET);// to struct hostent
cout<<"domain name: "<<phe->h_name<<endl;
cout<<std::hex<<"ip address (network byte order): "<<*((unsigned long *)phe->h_addr_list[0])<<endl;
WSACleanup();
cout<<"press any key to quit."<<endl;
_getch();
return iretcode;
}
来源:CSDN
作者:zing2000
链接:https://blog.csdn.net/zing2008/article/details/104219887