简体   繁体   English

递增 IP 地址

[英]Increment IP address

In that program I want to increment IP address.在那个程序中,我想增加 IP 地址。 And I see output like that:我看到 output 是这样的:

125.23.45.67
126.23.45.67
127.23.45.67 
128.23.45.67
129.23.45.67
130.23.45.67
131.23.45.67
132.23.45.67
133.23.45.67
134.23.45.67

But I want to see output like this:但我想看到这样的 output :

124.23.45.67
124.23.45.68
124.23.45.68 
124.23.45.70
124.23.45.71
124.23.45.72
124.23.45.73
124.23.45.74
124.23.45.75
124.23.45.76

Here is program code:这是程序代码:

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#include "winsock2.h"
#pragma comment(lib,"wsock32.lib")

void main()
{
in_addr adr1;
in_addr adr2;
int i;

adr1.s_addr=inet_addr("124.23.45.67");
adr2.s_addr=inet_addr("as.34.34.56");
if (adr1.s_addr!=INADDR_NONE)
    cout << " adr1 correct" << endl;
else
    cout << " adr1 incorect " << endl;

if (adr2.s_addr!=INADDR_NONE)
    cout << " adr2 correct" << endl;
else
    cout << " adr2 incorect" << endl;

cout << inet_ntoa(adr1) << endl;
cout << inet_ntoa(adr2) << endl;

for (i=0;i<10;i++)
{
    adr1.s_addr ++;
    cout << inet_ntoa(adr1) << endl;
}
}

Big endian and little endian gets another one.大端和小端得到另一个。 Use htonl and ntohl to convert back and forth.使用 htonl 和 ntohl 来回转换。

for (i=0;i<10;i++)
{
    adr1.s_addr  = htonl(ntohl(adr1.s_addr) + 1);

    cout << inet_ntoa(adr1) << endl;
}

To increment an IP address you will need to break up the in_addr object into 4 int objects (a short int will also do) and increment the 4th one until it hits 256, and then reset it to 1 and increment the 3rd one, etc. You shouldn't be using ++ on the in_addr object directly.要增加 IP 地址,您需要将in_addr object 分解为 4 个int对象( short int也可以)并增加第 4 个直到达到 256,然后将其重置为 1 并增加第 3 个,等等。您不应该直接在in_addr object 上使用++

EDIT: Okay, so you can properly increment it if you reverse the byte order.编辑:好的,所以如果你颠倒字节顺序,你可以适当地增加它。 I personally wouldn't do it that way.我个人不会那样做。 Especially if all you're doing is outputting IP strings and not using them as an in_addr elsewhere in code.特别是如果您所做的只是输出 IP 字符串,而不是将它们用作代码中其他地方的in_addr

Instead of using adr1.s_addr :而不是使用adr1.s_addr

adr1.s_addr=inet_addr("124.23.45.67");
adr2.s_addr=inet_addr("as.34.34.56"); 

Use this:用这个:

u_long addr1=inet_addr("124.23.45.67");

And increment addr1 , ie addr1++ the last octet gets incremented.并递增addr1 ,即addr1++最后一个八位字节递增。

Or follow this formula:或遵循以下公式:

if IP is A.B.C.D then u_long addr = A + 256*B + 256*256*C + 256*256*256*D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM