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:
Code:
struct in_addr
{
union
{
struct
{
u_char s_b1,
s_b2,
s_b3,
s_b4;
} S_un_b;
struct
{
u_short s_w1,
s_w2;
} S_un_w;
u_long S_addr;
} S_un;
};
Basically just a container for an unsigned long of course.
So to access byte[0] 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:
Code:
unsigned char
get_subnet(unsigned long address, int which)
{
return ((unsigned char*)&address)[which];
}
unsigned long
set_subnet(unsigned long * address, int which, unsigned char what)
{
((unsigned char*)address)[which] = what;
return *address;
}
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:
Code:
#define MAX 256
int main()
{
char buff[MAX];
unsigned long address;
int byte;
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);
printf("%s\n", inet_ntoa((in_addr&)address));
}
}
}
system("PAUSE");
}
>> 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.
Happy coding.