// GetHostIpAdd.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <Winsock2.h>
int _tmain(int argc, _TCHAR* argv[])
{
////////////////
// Initialize windows sockets API. Ask for version 1.1
//
WORD wVersionRequested = MAKEWORD(1, 1);
WSADATA wsaData;
if (WSAStartup(wVersionRequested, &wsaData)) {
printf("WSAStartup failed %s\n", WSAGetLastError());
return -1;
}
//////////////////
// Get host name.
//
char hostname[256];
int res = gethostname(hostname, sizeof(hostname));
if (res != 0) {
printf("Error: %u\n", WSAGetLastError());
return -1;
}
printf("hostname=%s\n", hostname);
////////////////
// Get host info for hostname.
//
hostent* pHostent = gethostbyname(hostname);
if (pHostent==NULL) {
printf("Error: %u\n", WSAGetLastError());
return -1;
}
//////////////////
// Parse the hostent information returned
//
hostent& he = *pHostent;
printf("name=%s\naliases=%s\naddrtype=%d\nlength=%d\n",
he.h_name, he.h_aliases, he.h_addrtype, he.h_length);
sockaddr_in sa;
for (int nAdapter=0; he.h_addr_list[nAdapter]; nAdapter++) {
memcpy(&sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
// Output the machines IP Address.
printf("Address: %s\n", inet_ntoa(sa.sin_addr)); // display as string
///printf("Address: %s\n", inet_ntoa((sockaddr_in*)(sa.sin_addr))); // display as string
}///
//////////////////
// Terminate windows sockets API
//
WSACleanup();
system("pause");
return 0;
}
property->link->依赖项 add ws2_32.lib.
//
#include "stdafx.h"
#include <stdio.h>
#include <Winsock2.h>
int _tmain(int argc, _TCHAR* argv[])
{
////////////////
// Initialize windows sockets API. Ask for version 1.1
//
WORD wVersionRequested = MAKEWORD(1, 1);
WSADATA wsaData;
if (WSAStartup(wVersionRequested, &wsaData)) {
printf("WSAStartup failed %s\n", WSAGetLastError());
return -1;
}
//////////////////
// Get host name.
//
char hostname[256];
int res = gethostname(hostname, sizeof(hostname));
if (res != 0) {
printf("Error: %u\n", WSAGetLastError());
return -1;
}
printf("hostname=%s\n", hostname);
////////////////
// Get host info for hostname.
//
hostent* pHostent = gethostbyname(hostname);
if (pHostent==NULL) {
printf("Error: %u\n", WSAGetLastError());
return -1;
}
//////////////////
// Parse the hostent information returned
//
hostent& he = *pHostent;
printf("name=%s\naliases=%s\naddrtype=%d\nlength=%d\n",
he.h_name, he.h_aliases, he.h_addrtype, he.h_length);
sockaddr_in sa;
for (int nAdapter=0; he.h_addr_list[nAdapter]; nAdapter++) {
memcpy(&sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
// Output the machines IP Address.
printf("Address: %s\n", inet_ntoa(sa.sin_addr)); // display as string
///printf("Address: %s\n", inet_ntoa((sockaddr_in*)(sa.sin_addr))); // display as string
}///
//////////////////
// Terminate windows sockets API
//
WSACleanup();
system("pause");
return 0;
}
property->link->依赖项 add ws2_32.lib.
梦想与现实的落差,就是我们离成功的距离~
![](http://www.cnblogs.com/Emoticons/others/look001.gif)