转载:c++获取本机IP地址
windows下获取IP地址的两种方法;
一种可以获取IPv4和IPv6,但是需要WSAStartup;
一种只能取到IPv4,但是不需要WSAStartup;
如下:
方法一:(可以获取IPv4和IPv6)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <Winsock2.h>
#include <stdio.h>
#include <iostream>
#include <cstring>
#include<ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib ") //linking to the library
using namespace std;
int get_ip()
{
struct addrinfo *ailist, *aip;
struct addrinfo hint;
struct sockaddr_in6 *sinp6;
PHOSTENT hostinfo;
char hostname[] = {}; //主机名
char *port = ""; //端口号
const char *addr;
int ilRc;
gethostname(hostname, sizeof(hostname));
if((hostinfo = gethostbyname(hostname)) == NULL) //获得本地ipv4地址
{
errno = GetLastError();
fprintf(stderr,"gethostbyname Error:%d\n", errno);
return ;
}
LPCSTR ip;
while(*(hostinfo->h_addr_list) != NULL) //输出ipv4地址
{
ip = inet_ntoa(*(struct in_addr *) *hostinfo->h_addr_list);
printf("ipv4 addr = %s\n\n", ip);
hostinfo->h_addr_list++;
}
hint.ai_family = AF_INET6; //hint 的限定设置
hint.ai_socktype = SOCK_STREAM; //这里可是设置 socket type 比如 SOCK_DGRAM
hint.ai_flags = AI_PASSIVE; // flags 的标志很多。常用的有AI_CANONNAME;
hint.ai_protocol = ; //设置协议 一般为0,默认
hint.ai_addrlen = ; //下面不可以设置,为0,或者为NULL
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
ilRc = getaddrinfo(hostname, port, &hint, &ailist); //通过主机名获得地址信息
if (ilRc < )
{
char str_error[];
strcpy(str_error, (char *)gai_strerror(errno));
printf("str_error = %s", str_error);
return ;
}
if(ailist == NULL)
{
printf("sorry not find the IP address,please try again \n");
}
for (aip = ailist; aip != NULL; aip = aip->ai_next) //显示获取的信息
{
aip->ai_family == AF_INET6;
sinp6 = (struct sockaddr_in6 *)aip->ai_addr; //为什么是for 循环 ,先向下看
int i;
printf("ipv6 addr = ");
for(i = ; i < ; i++)
{
if(((i-)%) && (i>))
{
printf(":");
}
printf("%02x",sinp6->sin6_addr.u.Byte[i]);
}
printf(" \n");
printf(" \n");
}
while();
}
int main(){ WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( , );
err = WSAStartup( wVersionRequested, &wsaData );//initiate the ws2_32.dll and match the version
if ( err != )
{
return ;
}
if ( LOBYTE( wsaData.wVersion ) != || //if the version is not matched ,then quit and terminate the ws3_32.dll
HIBYTE( wsaData.wVersion ) != )
{
WSACleanup( );
return ;
}
get_ip();
WSACleanup( );
return ;
}
方法二:(只能取到IPv4)
//#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <Iphlpapi.h>
#include <iostream>
using namespace std;
#pragma comment(lib,"Iphlpapi.lib") //需要添加Iphlpapi.lib库
//#pragma comment(lib, "ws2_32.lib") int main(int argc, char* argv[])
{
//PIP_ADAPTER_INFO结构体指针存储本机网卡信息
PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
//得到结构体大小,用于GetAdaptersInfo参数
unsigned long stSize = sizeof(IP_ADAPTER_INFO);
//调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量;其中stSize参数既是一个输入量也是一个输出量
int nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
//记录网卡数量
DWORD netCardNum = 0;
GetNumberOfInterfaces(&netCardNum);
cout << "网卡数量:" << netCardNum<< endl; netCardNum = 0;
//记录每张网卡上的IP地址数量
int IPnumPerNetCard = 0;
if (ERROR_BUFFER_OVERFLOW == nRel)
{
//如果函数返回的是ERROR_BUFFER_OVERFLOW
//则说明GetAdaptersInfo参数传递的内存空间不够,同时其传出stSize,表示需要的空间大小
//这也是说明为什么stSize既是一个输入量也是一个输出量
//释放原来的内存空间
delete pIpAdapterInfo;
//重新申请内存空间用来存储所有网卡信息
pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
//再次调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量
nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
}
if (ERROR_SUCCESS == nRel)
{
//输出网卡信息
//可能有多网卡,因此通过循环去判断
while (pIpAdapterInfo)
{
cout << "网卡序号:" << ++netCardNum <<"\t"<<pIpAdapterInfo->Index << endl;
cout << "网卡名称:" << pIpAdapterInfo->AdapterName << endl;
cout << "网卡描述:" << pIpAdapterInfo->Description << endl;
cout << "网卡类型:";
switch (pIpAdapterInfo->Type)
{
case MIB_IF_TYPE_OTHER: cout << "OTHER" << endl; break;
case MIB_IF_TYPE_ETHERNET: cout << "ETHERNET" << endl; break;
case MIB_IF_TYPE_TOKENRING: cout << "TOKENRING" << endl; break;
case MIB_IF_TYPE_FDDI: cout << "FDDI" << endl; break;
case MIB_IF_TYPE_PPP: cout << "PPP" << endl; break;
case MIB_IF_TYPE_LOOPBACK: cout << "LOOPBACK" << endl; break;
case MIB_IF_TYPE_SLIP: cout << "SLIP" << endl; break;
default: cout << "" << endl; break;
}
cout << "网卡MAC地址:";
for (DWORD i = 0; i < pIpAdapterInfo->AddressLength; i++)
if (i < pIpAdapterInfo->AddressLength - 1)
{
printf("%02X-", pIpAdapterInfo->Address[i]);
}
else
{
printf("%02X\n", pIpAdapterInfo->Address[i]);
}
cout << "网卡IP地址如下:" << endl;
IPnumPerNetCard = 0;
//可能网卡有多IP,因此通过循环去判断
IP_ADDR_STRING *pIpAddrString = &(pIpAdapterInfo->IpAddressList);
do
{
cout << "该网卡上的IP数量:" << ++IPnumPerNetCard << endl;
cout << "IP 地址:" << pIpAddrString->IpAddress.String << endl;
cout << "子网掩码:" << pIpAddrString->IpMask.String << endl;
cout << "网关地址:" << pIpAdapterInfo->GatewayList.IpAddress.String << endl;
pIpAddrString = pIpAddrString->Next;
} while (pIpAddrString);
pIpAdapterInfo = pIpAdapterInfo->Next;
cout << "--------------------------------------------------------------------" << endl;
} }
//释放内存空间
if (pIpAdapterInfo)
{
delete pIpAdapterInfo;
}
return 0;
}
Linux下,详见:http://www.cnblogs.com/lzpong/p/6956439.html
转载:c++获取本机IP地址的更多相关文章
- java获取本机IP地址
转载自:http://blog.csdn.net/thunder09/article/details/5360251 在网上找了几个用java获取本机IP地址的代码,发现都少都有些不完美,自己整理了一 ...
- 获取本机IP地址
这里有两种方法: //获取本机IP - (NSString *)localIPAddress { NSString *localIP = nil; struct ifaddrs *addrs; ) { ...
- 关于是用dotnet获取本机IP地址+计算机名的方法
印象中在maxscript帮助文档里找到过方法,但是当时没记下来.只能通过dotnet实现了. 如果电脑有无线网卡和本地连接,可能会出现乱码,也问了写dotnet的朋友,提供了一些思路,不过最终还是使 ...
- Windows下获取本机IP地址方法介绍
Windows下获取本机IP地址方法介绍 if((hostinfo = gethostbyname(name)) != NULL) { #if 1 ; printf("IP COUNT: % ...
- [转载]C#获取本机IPv4地址
C#获取本机IP地址在C#1.0之后都使用下面的这种形式: IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipa=i ...
- C# 获取本机IP地址以及转换字符串
/// <summary> /// IP地址转化 /// </summary> /// <param name="ipaddr">整型的IP地址 ...
- QT5下获取本机IP地址、计算机名、网络连接名、MAC地址、子网掩码、广播地址
获取主机名称 /* * 名称:get_localmachine_name * 功能:获取本机机器名称 * 参数:no * 返回:QString */ QString CafesClient::get_ ...
- 详谈再论JAVA获取本机IP地址
首先,你如果搜索“JAVA获取本机IP地址”,基本上搜到的资料全是无用的.比如这篇:http://www.cnblogs.com/zrui-xyu/p/5039551.html实际上的代码在复杂环境下 ...
- Linux下获取本机IP地址的代码
Linux下获取本机IP地址的代码,返回值即为互联网标准点分格式的字符串. #define ETH_NAME "eth0" //获得本机IP地址 char* GetLocalAdd ...
- shell中获取本机ip地址
shell中获取本机ip地址 方法一: /sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr ...
随机推荐
- 关于windbg报错"No symbols for ntdll. Cannot continue."问题
最近我写个例子程序研究下某个异常情况,故意制造了个崩溃.然后分析dmp文件. 当我执行!address -summary命令想观察下进程当前内存情况时,去报如下错误: 0:000> !addre ...
- Redis的移库操作
1.Redis默认有16个数据库,一般情况下使用0库: 2.移库操作: 将mysets移到一号库: 通过Redis查看器查看: 通过命令查看:
- centos 较新版本kernel安装方法
有时因为系统内核的bug 我们必须要安装新版本的kernel 来解决问题,有几种方法 源码编译 使用编译好的包 使用包的方式比较方便,同时一些依赖的问题可以自动帮助我们处理 添加yum 源 rpm - ...
- ubuntu 基于windows
windows10下的ubuntu子系统 wsl windows server linux ubuntu在微软商店可下载,安装好之后配置一个用户名和密码,默认的root用户时没有密码的.需要使用roo ...
- Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because ...
- CSS3 之书页阴影效果
视觉如下: CSS3 之书页阴影效果: <html> <head> <meta charset="UTF-8"> <title>书页 ...
- 解决Git - git push origin master 报错
关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 欢迎大家关注我的微信公众号:「醉翁猫咪」 原因:github仓库中没有README.md文件 解决如下: 重新输入git push ...
- Brexit Gym - 101490C
题目链接:Brexit vector的使用(vector存边),巧用queue,相当于Bfs /* */ # include <iostream> # include <cstdio ...
- Android App专项测试
https://www.jianshu.com/p/141b84f14505 http://www.cnblogs.com/finer/p/9601140.html 专项 概念 adb命令 App启动 ...
- 第12组 Alpha冲刺(5/6)
Header 队名:To Be Done 组长博客 作业博客 团队项目进行情况 燃尽图(组内共享) 展示Git当日代码/文档签入记录(组内共享) 注: 由于GitHub的免费范围内对多人开发存在较多限 ...