There's an even easier way.
Ip's are stored as unsigned long integers. That's 4 bytes of data.
To manipulate these bytes 'easily', the creators of the socket specification came up with this ridiculous structure:
Basically just a container for an unsigned long of course.
So to access byte we 'simply' navigate to in_addr::S_un.S_un_b.s_b1 (!)
That's a bit complicated for such a trivial task!
So here's a simpler approach:
get_subnet(unsigned long address, int which)
return ((unsigned char*)&address)[which];
set_subnet(unsigned long * address, int which, unsigned char what)
((unsigned char*)address)[which] = what;
Of course, the above could be coded as a macro, if necessary.
So here's an example of putting this simple little scheme to work:
#define MAX 256
unsigned long address;
printf("Enter a valid ip address > ");
fgets(buff, MAX, stdin);
if((address = inet_addr(buff)) != INADDR_NONE)
printf("Which subnet to manipulate? [0-3] > ");
if((byte = atoi(fgets(buff, MAX, stdin))) < 4)
for(int i = get_subnet(address, byte)+1; i < MAX; ++i)
set_subnet(&address, byte, i);
>> int abc = sscanf(ipadd, "%3u.%3u.%3u.%3u%c", &b1, &b2, &b3, &b4, &c);
That's not really necessary. The inet_addr() function takes a dotted decimal string and converts it to an unsigned long.
Then you have the inet_ntoa() function that does just opposite (though you have to cast the unsigned long to an in_addr).
So between the two, you can convert back and forth rather easily, ie:
printf("%s", inet_ntoa(inet_addr(inet_ntoa(inet_addr("127.0.0.1 ")))));
- prints "127.0.0.1", of course.
Anyway, I hope that helps.