VC++获取本机所有IP和掩码信息

// GetIPs.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <atlstr.h>
#include <IPHlpApi.h>
//#include <WinSock2.h>
#include <iostream>

//#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Iphlpapi.lib")

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

	CString szMark;


	PIP_ADAPTER_INFO pAdapterInfo;
	PIP_ADAPTER_INFO pAdapter = NULL; 
	DWORD dwRetVal = 0; 

	pAdapterInfo = ( IP_ADAPTER_INFO * ) malloc( sizeof( IP_ADAPTER_INFO ) );
	ULONG ulOutBufLen; 
	ulOutBufLen = sizeof(IP_ADAPTER_INFO); 



	// 第一次调用GetAdapterInfo获取ulOutBufLen大小 
	if (GetAdaptersInfo( pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) 
	{ 
		free(pAdapterInfo);
		pAdapterInfo = (IP_ADAPTER_INFO *) malloc (ulOutBufLen); 
	} 

	if ((dwRetVal = GetAdaptersInfo( pAdapterInfo, &ulOutBufLen)) == NO_ERROR) 
	{ 
		pAdapter = pAdapterInfo; 
		while (pAdapter) 
		{
			PIP_ADDR_STRING pIPAddr;
			pIPAddr = &pAdapter->IpAddressList;
			while (pIPAddr)
			{
				cout << "IP:" << pIPAddr->IpAddress.String << endl;
				cout << "Mask:" << pIPAddr->IpMask.String << endl;
				cout << endl;
				pIPAddr = pIPAddr->Next;
			}
			pAdapter = pAdapter->Next; 
		} 
	} 

	
	getchar();
	return 0;
}

#include "stdafx.h"
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<winsock2.h>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;

#define ERR_EXIT(m) \
	do\
{\
	perror(m);\
	exit(EXIT_FAILURE);\
}while(0)

int getlocalip(char *ip)
{
	char host[100] ={"sina.com.cn"};
	if(gethostname(host,sizeof(host))<0)
		return -1;
	struct hostent *hp;
	if((hp =gethostbyname(host))==NULL)
		return -1;
	strcpy(ip,inet_ntoa(*(struct in_addr*)hp->h_addr));  //h_addr代表主机IP
	return 0;
}
int main()
{
	WSADATA wsd;

	if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
	{
		cout<<"WSAStartup failed!"<<endl;
		ERR_EXIT("WSAStartup");
	}

	char host[100] ={0};
	if(gethostname(host,sizeof(host)) ==SOCKET_ERROR)  //获取主机名
		ERR_EXIT("gethostname");

	struct hostent *hp;
	if((hp = gethostbyname(host)) ==NULL)  //通过主机名获取更多信息
		ERR_EXIT("gethostbyname");

	int i =0;
	while(hp->h_addr_list[i]!=NULL)
	{
		printf("%s\n",inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
		i++;
	}

	char ip[16] ={0};
	getlocalip(ip);
	printf("localip =%s\n",ip);

	getchar();
	return 0;   
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值