增加IP地址

d_p*_*lot 9 c++ windows network-programming inetaddress

在那个程序中我想增加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
Run Code Online (Sandbox Code Playgroud)

但我希望看到这样的输出:

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
Run Code Online (Sandbox Code Playgroud)

这是程序代码:

#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;
}
}
Run Code Online (Sandbox Code Playgroud)

sel*_*bie 20

Big endian和little endian获得另一个!使用htonl和ntohl来回转换.

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

    cout << inet_ntoa(adr1) << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 有点历史。早在 90 年代,当 Sun 以其 Sparc 架构统治 Unix 星球时。没有人会正确使用字节序转换函数,因为他们不需要。然后 x86 上的 Linux 与 Winsock 大约在同一时间出现。将网络代码移植到这些新平台真的很烦人——因为它可以编译得很好,但实际上不起作用。 (2认同)

dar*_*s0n 6

要增加IP地址,您需要将in_addr对象分解为4个int对象(a short int也会这样做)并递增第4个对象,直到它达到256,然后将其重置为1并增加第3个,等等.你不应该直接++in_addr对象上使用.

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