获取局域网中所有主机与IP地址

 // GetLANIP.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <afxtempl.h> #include <WINSOCK2.H> #pragma comment(lib,"Ws2_32.lib") #pragma comment(linker, "/defaultlib:kernel32.lib") #pragma comment(linker, "/OPT:NOWIN98") int GetHostList(CStringArray& caHostList); int main(int argc, char* argv[]) { // printf("Hello World!/n"); CStringArray caHostList; int nNumOfhosts=0; nNumOfhosts = GetHostList(caHostList); printf("Number of Hosts: %d/n",nNumOfhosts); for(int i=0;i<nNumOfhosts;i++) { printf("%s",caHostList[i]); } system("pause");//暂停屏幕 return 0; } int GetHostList(CStringArray& caHostList) { WORD wsaVersion; WSADATA WSAData; wsaVersion=MAKEWORD(2,0); if(WSAStartup(wsaVersion,&WSAData)==SOCKET_ERROR) { return 0; } FILE *bat=fopen("host.bat","wb"); if(bat==NULL) return 0; fputs("@echo off/r/n",bat); fputs("net view|find /"/////">host.txt/r/n",bat);//把命令写入批处理文件,并且运行查找局域网中所有主机,并把主机名写入host.txt fputs("exit/r/n",bat); fclose(bat); system("host.bat");//运行批处理文件 remove("host.bat");//清除批处理文件 bat=fopen("host.txt","r"); if(bat==NULL) return 0; CString sHost,sHost2,sResult; int nRet=0; int nNumOfHosts=0; while (fgets(sHost.GetBufferSetLength(128),127,bat))//一行一行读入数据,写入sHost { sHost.ReleaseBuffer(128); nRet = sHost.Find(' ');//找到空格出现的位置,从0开始 sHost2 = sHost.Mid(2,nRet-2);//分离出2--nRet-2中的字符 hostent* pHostent = gethostbyname(sHost2);//获得主机名为sHost2的hostent结构体,此结构体中存放主机名与IP if (pHostent == NULL) continue; in_addr* pIpAddr; pIpAddr = (in_addr*)pHostent->h_addr_list[0]; sResult.Format("%-20s%s/n",sHost2,inet_ntoa(*pIpAddr));//把IP转化为字符,格式化主机名与IP caHostList.Add(sResult);//加入到CstringArray表中 nNumOfHosts++; } sHost.ReleaseBuffer(128); fclose(bat); remove("host.txt"); caHostList.SetSize(nNumOfHosts); caHostList.FreeExtra(); WSACleanup(); return caHostList.GetSize(); }

你可能感兴趣的:(socket,list,File,null,System,linker)