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 = ;
GetNumberOfInterfaces(&netCardNum);
cout << "网卡数量:" << netCardNum<< endl; netCardNum = 0;
//记录每张网卡上的IP地址数量
int IPnumPerNetCard = ;
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 = ; i < pIpAdapterInfo->AddressLength; i++)
if (i < pIpAdapterInfo->AddressLength - )
{
printf("%02X-", pIpAdapterInfo->Address[i]);
}
else
{
printf("%02X\n", pIpAdapterInfo->Address[i]);
}
cout << "网卡IP地址如下:" << endl;
IPnumPerNetCard = ;
//可能网卡有多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 ;
}

Linux下,详见:http://www.cnblogs.com/lzpong/p/6956439.html

windows 获取本机(全部)IPv4、IPv6、MAC地址方法 (C/C++)的更多相关文章

  1. Java获取本机的IP与MAC地址

    有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证: // 获取mac地址 public static String getMacAddress() { try { Enumer ...

  2. 获取客户机的ip和mac地址

    只获取clientIP package com.ppms.utils; import javax.servlet.http.HttpServletRequest; /** * Created by l ...

  3. C# 获取本机CPU序列号,MAC地址,硬盘ID,本机IP地址,计算机名,物理内存,PC类型

    首先引入服务 然后 调用 本文转载自http://blog.sina.com.cn/s/blog_7eeb43210101hf7f.html public class Computer { publi ...

  4. windows获取本机MAC地址并写入文件的bat

    windows获取本机MAC地址并写入文件的bat MAC(Media Access Control)地址,或称为 MAC地址.硬件地址,用来定义网络设备的位置. bat代码例如以下: @echo o ...

  5. Linux中获取本机的最新IPv6地址_更新ddns的脚本

    Linux中获取本机的最新IPv6地址_更新ddns的脚本 转载注明来源: 本文链接 来自osnosn的博客,写于 2019-11-07. 运营商提供ipv6地址. 路由器后有台linux机器,通过e ...

  6. 【转载】获取MAC地址方法大全

    From:http://blog.csdn.net/han2814675/article/details/6223617 Windows平台下用C++代码取得机器的MAC地址并不是一件简单直接的事情. ...

  7. C#获取IP及MAC地址 方法

    C#获取IP及MAC地址 方法,比较齐全 using System.Net; using System; using System.Management; using System.Runtime.I ...

  8. C++获取本机用于连接的IP地址

    最近写个程序需要获取本机用于连接的IP地址,经过很多的尝试后,最终使用的方法如下: 使用cmd命令    netstat  | findstr “192.168.6.66:3333” > D:\ ...

  9. 验证试验 更改了从机CAN通信的MAC地址 从机新挂CAN网络 上电自检通过

    更改前 该之后 主机程序 与 从机 程序 已经上传到网盘上 ,主机和从机程序基本一致, 唯一的区别是 从机更好了MAC地址 为0X10  主机的固定MAC地址为 0X1F 改程序的配置上设置的是双滤波 ...

随机推荐

  1. 《Advanced Bash-scripting Guide》学习(十五):测试坏的链接文件(broken link)

    本文所选的例子来自于<Advanced Bash-scripting Gudie>一书,译者 杨春敏 黄毅 #/bin/bash #用一个纯粹的shell脚本来找出坏链接文件 #什么是br ...

  2. LeetCode OJ:Construct Binary Tree from Inorder and Postorder Traversal(从中序以及后序遍历结果中构造二叉树)

    Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  3. canvas基础学习(三)

    一.图片加载控件 在canvas效果制作中常常要使用多张图片,为了提高用户体验,需要给用户提供一个图片加载中的过度页面效果.过度效果,我在项目中使用的是Sonic.js,它在git上的地址为https ...

  4. 网络爬虫必备知识之concurrent.futures库

    就库的范围,个人认为网络爬虫必备库知识包括urllib.requests.re.BeautifulSoup.concurrent.futures,接下来将结对concurrent.futures库的使 ...

  5. hexo博客相关

    https://www.cnblogs.com/sulishibaobei/p/6428241.html 利用hexo+github+nodejs搭建自我博客的一天 http://www.sulish ...

  6. Unity 5 官方打包管理工具 Asset Bundle Manager

    http://blog.csdn.net/suifcd/article/details/51570003 Unity5在Asset bundle 打包管理上采用了全新的方式,不需要再对每个文件进行MD ...

  7. Java处理乱码问题

    中文乱码分为GET乱码和POST乱码 GET乱码在Tomcat中配置编码 <Connector port="8080" protocol="HTTP/1.1&quo ...

  8. Dubbo模块介绍

    一.Dubbo 整体框架 Dubbo主要有:Config 配置层.Proxy服务代理层.Registry注册中心层.Cluster 路由层.Monitor监控层.Protocol远程调用层.Excha ...

  9. 5 Things You Should Know About the New Maxwell GPU Architecture

    The introduction this week of NVIDIA’s first-generation “Maxwell” GPUs is a very exciting moment for ...

  10. 根据VM的TAG开停机

    公有云一个非常大的优势,就是可以根据需求进行开停机.由于计费是按时进行的,从而实现节省成本. Azure上用脚本按时开停机已经有很多部署的案例.本文将介绍采用VM Tag中规定的时间进行开停机的脚本. ...