首页 > 代码库 > c语言 c++ 实现查看本地ip,外网ip, 本地主机名,查看http网址对应的ip
c语言 c++ 实现查看本地ip,外网ip, 本地主机名,查看http网址对应的ip
/*******************************************************************************作者 :邓中强Email :1246747572@qq.comQQ :1246747572博客 :http://www.cnblogs.com/dzqdzq/时间 :2014/01/01功能*******************************************************************************/#include "cstdio"#include "cstring"#include "string"#include "winsock2.h"#pragma comment(lib, "urlmon.lib")using namespace std;// 获取本机ipchar* getlocal_ip(){ char *ret; char host_name[256] = ""; WSADATA wsaData; WSAStartup(0x101, &wsaData); if (!gethostname(host_name, 256)) { ret = inet_ntoa(*((struct in_addr*)gethostbyname(host_name)->h_addr)); } WSACleanup(); return ret;}// 获取本机名char* getlocal_name(char *name,int len){ WSADATA wsaData; WSAStartup(0x101, &wsaData); gethostname(name, len); WSACleanup(); return name;}// 获取公网ip (也叫外网ip)char* getPub_ip(char *ip){ const char* dest = "<code>"; const char* dest1 = "</code>"; const char* szFileName = "D:/ip.txt"; if (URLDownloadToFile(NULL, "http://www.ip.cn/", szFileName, 0, NULL) == S_OK) { FILE *fp = fopen(szFileName, "r"); if (fp) { char line[512]; while (fgets(line,512,fp)) { char *fd = strstr(line, dest); if (fd) { char* star = fd + strlen(dest); strncpy(ip,star,strstr(star,dest1)-star);//16 break; } } fclose(fp); remove(szFileName);// 删除文件 } } return ip;}// 获取某个网站的ipchar* getipFromHttp(char *http,char *result){ const char* fileName = "D:/1.txt"; string cmd = string("ping ") + http + string(">") + fileName; system(cmd.c_str()); FILE *fp = fopen(fileName,"r"); if (fp) { char line[512]; while (fgets(line,512,fp)) { char *fd = strchr(line,‘[‘); if (fd) { char *star = fd + 1; strncpy(result, star, strchr(star,‘]‘)-star); break; } } fclose(fp); remove(fileName); } return NULL;}int main(){ char name[28] = ""; printf("本地IP:%s\n", getlocal_ip()); printf("主机名:%s\n", getlocal_name(name, 28)); char ip[25] = ""; printf("外网:%s\n", getPub_ip(ip)); char *http = "www.taobao.com"; getipFromHttp(http, ip); printf("%s --DNS--> %s\n",http,ip); system("pause"); return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。