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
但我希望看到这样的输出:
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;
}
}
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;
}
要增加IP地址,您需要将in_addr对象分解为4个int对象(a short int也会这样做)并递增第4个对象,直到它达到256,然后将其重置为1并增加第3个,等等.你不应该直接++在in_addr对象上使用.
编辑:好的,如果你颠倒字节顺序,你可以正确地增加它.我个人不会这样做.特别是如果您所做的只是输出IP字符串而不是将它们用作in_addr代码中的其他地方.
| 归档时间: | 
 | 
| 查看次数: | 2734 次 | 
| 最近记录: |