ip address octet increments

Hi all,

Situation is as below.
I would get an IP address and port from eithe r a file or command line. It probably would be as char * or string. So was wondering how I could accept this and increment the last octets?

Incrementing the port is fine. I could get that into an integer by atoi() and then increment it.
But the IP address part is getting tricky. Any say please?

There are two standard calls for this (for IPv4 address formats):
inet_addr() returns an integer
inet_ntoa() returns the dotted form

Take the dotted form, convert to integer, add one, convert back to dotted form.

thanks jim...
there is another way...the country road way :slight_smile:

char inputIpstring[16];
int oct1,oct2,oct3,oct4,
sscanf(inputIpString,"%d.%d.%d.%d",&oct1,&oct2,&oct3,&oct4)

increment anyof the octetes as you want and

sprintf(inputIpString,"%d.%d.%d.%d",oct1,oct2,oct3,oct4);

BTW, if I pass 225.10.20.30 and would need all the Ip addresses from 225.10.20.30 to 225.10.30.30 without the last octet being changed....that is

225.10.20.30
225.10.21.30
225.10.22.30
225.10.23.30
225.10.24.30

etc...

willt his work with the inet_addr() method,
Would I add 510 and I will get 225.10.21.30 from 225.10.20.30?

Try it and see - I've never used it that way. I believe the code works modulo 255 as you seem to indicate.

If you are shooting at enumerating the various ip addresses in your local network, there are more efficient ways than guessing ip's.

jim...nope doesnt work...
works for the last octet though ...and is not linear after that.
thanks anyway. wills stick with my old method.

That does not compute. How did you arrive at 510? Try 257.

perderabo...sorry my bad its 255 not 510.
and it scales up fine for the last ocet if we we keep incrementing from 1 to 255, but not after that.

My bad too. I wrote a quickie to try to increment the 3rd octet but I had the wrong increment. So I let the program compute the increments. Here it is...

$ cat sock.c
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

main(){
        struct in_addr a;
        int i;
        int incr;
        incr=inet_addr("255.10.20.30") - inet_addr("254.10.20.30");

        printf("1st incr = %d \n", incr);
        incr=inet_addr("255.11.20.30") - inet_addr("255.10.20.30");
        printf("2nd incr = %d \n", incr);
        incr=inet_addr("255.10.21.30") - inet_addr("255.10.20.30");
        printf("3rd incr = %d \n", incr);
        incr=inet_addr("255.10.20.31") - inet_addr("255.10.20.30");
        printf("4th incr = %d \n", incr);

        a.s_addr=inet_addr("255.10.20.30");
        for(i=0;i<5;i++) {
                printf("%s\n", inet_ntoa((struct in_addr) a));
                a.s_addr += 65536;
        }
        exit(0);
}
$ ./sock
1st incr = 1
2nd incr = 256
3rd incr = 65536
4th incr = 16777216
255.10.20.30
255.10.21.30
255.10.22.30
255.10.23.30
255.10.24.30
$

perderabo..thank you. will try to implement this.