【问题标题】:Increment IP address增加 IP 地址
【发布时间】:2011-10-08 06:39:02
【问题描述】:

在那个程序中,我想增加 IP 地址。我看到这样的输出:

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

但我想看到这样的输出:

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

这是程序代码:

#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;
}
}

【问题讨论】:

    标签: c++ windows network-programming inetaddress


    【解决方案1】:

    大端和小端又多了一个!使用 htonl 和 ntohl 来回转换。

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

    【讨论】:

    • +1,但翻转字节顺序似乎很骇人。 Other people 同意你的看法。
    • 对 IP 地址进行“数学运算”似乎很奇怪。当数学从子网生成 IP 地址时会发生什么?必须处理所有极端情况。
    • 一点历史。早在 90 年代,当 Sun 以其 Sparc 架构统治 Unix 星球时。没有人会正确使用字节序转换函数,因为他们不需要。然后 x86 上的 Linux 与 Winsock 几乎同时出现。将网络代码移植到这些新平台真的很烦人——因为它编译得很好,但实际上并不能工作。
    • @selbie:在指针上做数学看起来很奇怪。当数学从数组中生成一个指针时会发生什么?然而... ;-)
    • 我的意思是一个指针 (en.wikipedia.org/wiki/Pointer_%28computing%29#C_and_C.2B.2B)。人们对它们进行数学运算,尽管这种数学运算可能超出有效范围。做数学的人有责任避免这种情况。在此 IP 地址示例中,如果您知道子网掩码至少为 7 位,则 x.y.z.67 到 x.y.z.76 的范围不在子网范围内。
    【解决方案2】:

    要增加 IP 地址,您需要将 in_addr 对象分解为 4 个 int 对象(short int 也可以)并增加第 4 个直到达到 256,然后将其重置为 1并增加第三个等。您不应该直接在in_addr 对象上使用++

    编辑:好的,如果你颠倒字节顺序,你可以适当地增加它。我个人不会那样做。特别是如果您所做的只是输出 IP 字符串,而不是在代码的其他地方将它们用作 in_addr

    【讨论】:

    • 恕我直言,您的版本太复杂了。
    【解决方案3】:

    而不是使用adr1.s_addr:

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

    使用这个:

    u_long addr1=inet_addr("124.23.45.67");
    

    并增加addr1,即addr1++ 最后一个八位字节递增。

    或者按照这个公式:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 2023-02-22
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 2011-03-29
      • 2021-12-30
      • 1970-01-01
      相关资源
      最近更新 更多