//#include <windows.h>
//#include "string"
//using namespace std;
// #include "winsock.h"
//#pragma comment( lib, "ws2_32.lib" )
//
////int GetIPAddress(const string& sHostName, string& sIPAddress) // 获取IP地址
////{
//// struct hostent *lpHostEnt = gethostbyname(sHostName);
//// if (lpHostEnt == NULL)
//// {
//// sIPAddress = "";
//// return WSAGetLastError();
//// }
//// LPSTR lpAddr = lpHostEnt->h_addr;
//// if (lpAddr)
//// {
//// struct in_addr inAddr;
//// memmove(&inAddr, lpAddr, 4); // 将地址进行转换成常规形式
//// sIPAddress = inet_ntoa(inAddr);
//// }
//// return 0;
////}
//bool GetTheLocalIP(char* ip)
//{
// //1.初始化wsa
// WSADATA wsaData;
// int ret=WSAStartup(MAKEWORD(2,2),&wsaData);
// if (ret!=0)
// {
// return false;
// }
// //2.获取主机名
// char hostname[256];
// ret=gethostname(hostname,sizeof(hostname));
// if (ret==SOCKET_ERROR)
// {
// return false;
// }
// //3.获取主机ip
// /* HOSTENT* host=gethostbyname(hostname);
// if (host==NULL)
// {
// return false;
// } */
// struct hostent *lpHostEnt = gethostbyname(hostname);
// if (lpHostEnt == NULL)
// {
// return WSAGetLastError();
// }
// LPSTR lpAddr = lpHostEnt->h_addr;
// if (lpAddr)
// {
// struct in_addr inAddr;
// memmove(&inAddr, lpAddr, 4); // 将地址进行转换成常规形式
// string sIPAddress = inet_ntoa(inAddr);
// }
// //4.转化为char*并拷贝返回
// // strcpy(ip,inet_ntoa(*(in_addr*)*host->h_addr_list));
// return true;
//}
//
//int main()
//{
// char* ip = NULL;
// GetTheLocalIP(ip);
//}
#include"stdio.h"
#include"string.h"
#include"Winsock2.h"
#pragma comment(lib,"WS2_32.lib")
void main()
{ /*printf("********************************\n");
printf("方法一,精确输出\n"); */
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData)==SOCKET_ERROR)
{
exit(0);
}
int nLen=256;
char hostname[20];
gethostname(hostname,nLen);
hostent *pHost = gethostbyname(hostname);
/*LPSTR lpAddr = pHost->h_addr_list[0];
struct in_addr inAddr;
memmove(&inAddr,lpAddr,4);
printf("有 线 IP地址:%s\n",inet_ntoa(inAddr));
memmove(&inAddr,lpAddr+4,4);
printf("无 线 IP地址:%s\n",inet_ntoa(inAddr));
memmove(&inAddr,lpAddr+8,4);
printf("环 回 IP地址:%s\n",inet_ntoa(inAddr));
memmove(&inAddr,lpAddr+12,4);
printf("虚拟机1 IP地址:%s\n",inet_ntoa(inAddr));
memmove(&inAddr,lpAddr+16,4);
printf("虚拟机2 IP地址:%s\n",inet_ntoa(inAddr));
printf("********************************\n\n");
printf("********************************\n");
printf("方法二,打印所有Ip,验证第一次输出\n"); */
char szHost[256] = {0};
hostent *lpHost = gethostbyname(szHost);
memset(szHost,0,sizeof(szHost));
// 取得本地主机名称
::gethostname(szHost, 256);
// 通过主机名得到地址信息
// 打印出所有IP地址
in_addr addr;
for(int i = 0; ; i++)
{
char *p = lpHost->h_addr_list[i];
if(p == NULL)
break;
memcpy(&addr.S_un.S_addr, p, lpHost->h_length);
char *szIp = ::inet_ntoa(addr);//将32位的二进制数转化为字符串;
printf("本机IP地址:%s \n", szIp);
}
printf("********************************\n");
::WSACleanup();
system("pause");
}
C++获取本机IP......
5星 · 超过95%的资源 需积分: 15 145 浏览量
2017-09-04
17:47:25
上传
评论
收藏 12.25MB RAR 举报
vge_
- 粉丝: 2
- 资源: 23