Increment IP address Increment IP address windows windows

Increment IP address


Big endian and little endian gets another one! Use htonl and ntohl to convert back and forth.

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.

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.


Instead of using 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, i.e. addr1++the last octet gets incremented.

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