#include <iostream.h>
#include <winsock2.h>
#pragma comment(lib,"Ws2_32")
char* getIPAddrbyName(char* name)
{
hostent* hostIP;
WSADATA wsd;
char *IPAddr, *PtrAddr;
struct in_addr inAddr;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
cout<<"套接字初始化失败"<<endl;
return NULL;
}
hostIP = gethostbyname(name);
if (WSAGetLastError() != 0)
{
if (WSAGetLastError() == 11001)
{
cout<<"主机没有找到"<<endl;;
return NULL;
}
}
else
{
inAddr.S_un.S_addr = *((unsigned long *)hostIP->h_addr_list[0]);
PtrAddr = inet_ntoa(inAddr);
WSACleanup();
IPAddr = new char[strlen(PtrAddr)+1];
strcpy(IPAddr, PtrAddr);
}
return IPAddr;
}
void main()
{
char buffer[1024];
char* IPName;
cout<<"please input the name which you want to get IPAddress:"<<endl;
cin>>buffer;
IPName = buffer;
IPName = getIPAddrbyName(IPName);
if(IPName != NULL)
cout<<"IP is "<<IPName<<endl;
}
//根据IP地址得到机器名称
//----------------------
// Declare and initialize variables
hostent* remoteHost;
char* host_name;
unsigned int addr;
//----------------------
// User inputs name of host
printf("Input name of host: ");
host_name = (char*) malloc(sizeof(char*)*16);
fgets(host_name, 16, stdin);
// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
if (isalpha(host_name[0])) { /* host address is a name */
host_name[strlen(host_name)-1] = '/0'; /* NULL TERMINATED */
remoteHost = gethostbyname(host_name);
}
else {
addr = inet_addr(host_name);
remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
}
if (WSAGetLastError() != 0) {
if (WSAGetLastError() == 11001)
printf("Host not found.../nExiting./n");
}
else
printf("error#:%ld/n", WSAGetLastError());
// The remoteHost structure can now be used to
// access information about the host
//----------------------
// Declare and initialize variables
hostent* remoteHost;
char* host_name;
unsigned int addr;
//----------------------
// User inputs name of host
printf("Input name of host: ");
host_name = (char*) malloc(sizeof(char*)*16);
fgets(host_name, 16, stdin);
// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
if (isalpha(host_name[0])) { /* host address is a name */
host_name[strlen(host_name)-1] = '/0'; /* NULL TERMINATED */
remoteHost = gethostbyname(host_name);
}
else {
addr = inet_addr(host_name);
remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
}
if (WSAGetLastError() != 0) {
if (WSAGetLastError() == 11001)
printf("Host not found.../nExiting./n");
}
else
printf("error#:%ld/n", WSAGetLastError());
// The remoteHost structure can now be used to
// access information about the host
//根据socket取得IP地址/
::getpeername(s, &ipAddr, &Len);