-1

I need help in writing a function in C/C++ that receives two parameters: IP address and subnetmask.

The function needs to reutrn a list of all IP addresses that are in the associated network.

For example: Given two parameters: IP address = 192.168.33.72 and mask = 255.255.255.192 the function will return a list that contain the IP's 192.168.33.65 to 192.168.33.126.

unwind
  • 364,555
  • 61
  • 449
  • 578
RajedBuli
  • 13
  • 1
  • 3

1 Answers1

3

1) first you can transform the ipaddress and the subnetmask from string format to binary format with inet_pton().

2) make a check on the subnetmask mask it should be a valid subnet mask

3) get the subnetmask inverse value (~subnetmask)

4)

for (i=1; i<(~subnetmask); i++) {

    ip = ipaddress & (subnetmask + i);

    //append ip to your ip list

}
MOHAMED
  • 35,883
  • 48
  • 140
  • 238
  • There is nothing that says a subnetmask can't have the LSB set... in which case your code will generate a bunch of invalid ip addresses. – Floris Nov 01 '13 at 14:55
  • @Floris what LSB mean? means the first bit in the binary format of the subnetmask? – MOHAMED Nov 01 '13 at 15:01
  • LSB = least significant bit. Imagine the mask is 255.255.255.193 - see what happens in your code. – Floris Nov 01 '13 at 15:29
  • @Floris LSB could be set to 1 in the subnemask in only 1 case: if the `subnetmask = 255.255.255.255` otherwise you can not set the subnetmask LSB to 1. The example you give `255.255.255.193` is not a valid subnet mask: see http://en.wikipedia.org/wiki/IPv4_subnetting_reference. And that's why in my answer I said that we have to check if the `subnetmask` is a valid subnet mask (step 2) – MOHAMED Nov 01 '13 at 15:56