/* 编译环境: visual c++ */
#include
#include
#pragma comment(lib,"ws2_32.lib")
int doit(int, char **)
{
char host_name[255];
//获取本地主机名称
if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {
printf("Error %d when getting local host name.n", WSAGetLastError());
return 1;
}
printf("Host name is: %sn", host_name);
//从主机名数据库中得到对应的“主机”
struct hostent *phe = gethostbyname(host_name);
if (phe == 0) {
printf("Yow! Bad host lookup.");
return 1;
}
//循环得出本地机器所有IP地址
for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
printf("Address %d : %sn" , i, inet_ntoa(addr));
}
return 0;
}
int main(int argc, char *argv[])
{
WSAData wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
return 255;
}
int retval = doit(argc, argv);
WSACleanup();
return retval;
}
system("ipconfig /all>1.txt");
然后fopen打开1.txt这个文件,按行读取,判断是不是IP地址然后存储
#include
#include
#include
int main(int argc, char *argv[]) {
system("ipconfig/all");
int i, j;
char ip[25];
char temp[100];
FILE*fp;
system("ipconfig >c:\\ip.txt");
if ((fp = fopen("c:\\ip.txt", "r")) == NULL ) {
exit(1);
}
for (i = 0; i < 7; i++) {
fgets(temp, 90, fp);
// printf("%s\n",temp);
}
fgets(temp, 90, fp);
i = 0;
j = 0;
while (temp[i++] != ':'&& temp[i] != '\n')
;
ip[j++] = temp[i++];
ip[j] = 0;
printf("IP=%s\n", ip);
fclose(fp);
system("del c:\\ip.txt");
return 0;
}