// ipv6.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WS2tcpip.h>
#include <iostream>
#include <WinSock2.h>
#include <string>
using namespace std;
#pragma comment(lib, "Ws2_32.lib")
//输出ipv4的所有地址
int func()
{
string startIPAddr, endIPAddr;
unsigned long startIP, endIP, index;
cout << "input start and end IP" << endl;
cin >> startIPAddr >> endIPAddr;
startIP = htonl(inet_addr(startIPAddr.c_str()));
endIP = htonl(inet_addr(endIPAddr.c_str()));
if (startIP > endIP)
{
cout << "startIP must be smaller than endIP" << endl;
return 1;
}
else
{
struct in_addr addr;
//遍历输出ip段的所有地址。
for (index = startIP; index <= endIP; index++)
{
addr.S_un.S_addr = ntohl(index);
cout << inet_ntoa(addr) << "\n";
}
}
}
//输出ipv6段的所有地址,下面的逻辑只做参考,可以根据自己的需求进行修改
vector<std::string> vecIpAddr;
void funIP6(std::string strIpStart,std::string strIpEnd)
{
int nIndex1 = strIpStart.rfind(":");
string strFiledIpStart = strIpStart.substr(nIndex1+1);
uint64_t nIpStart = strtol(strFiledIpStart.c_str(),NULL,16);
int nIndex2 = strIpEnd.rfind(":");
string strFiledIpEnd = strIpEnd.substr(nIndex2 + 1);
uint64_t nIpEnd = strtol(strFiledIpEnd.c_str(), NULL, 16);
string strIpNew = "";
char chIp[5] = {0};
for (; nIpStart <= nIpEnd;nIpStart++)
{
_snprintf_s(chIp,sizeof(chIp)-1,"%04x", nIpStart);
strIpNew = strIpStart.substr(0,nIndex1 + 1) + string(chIp);
vecIpAddr.push_back(strIpNew);
::memset(chIp,0,sizeof(chIp));
}
}
int main()
{
std::cout << "Hello World!\n";
//char IPdotdec[20]; //存放点分十进制IP地址
//struct in_addr s; // IPv4地址结构体
输入IP地址
//printf("Please input IP address: ");
//scanf_s("%s", IPdotdec,20);
转换
//inet_pton(AF_INET, IPdotdec, (void *)&s);
//char IPdotdec[200]; //存放点分十进制IP地址
//struct in_addr6 s; // IPv4地址结构体
输入IP地址
//printf("Please input IP address: ");
//scanf_s("%s", IPdotdec, 200);
转换
//inet_pton(AF_INET6, IPdotdec, (void *)&s);//可以在将点分文本的IP地址转换为二进制网络字节序”的IP地址
//inet_pton(AF_INET6, IPdotdec, (void *)&s);其实使用此函数也可以遍历ipv6,有兴趣的可以自己写
func();
funIP6("1111::ff","2222::ffff");
}
注:编译有错误 error C4996: ‘inet_addr’: Use inet_pton() or InetPton() instead or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API warnings的话,可以使用下面方法解决,也可以使用新函数替换。