Programmatically adding Static IP's

Go To StackoverFlow.com

1

I am writing a small application to automated a lot of the stuff we have to do on a daily basis when setting up new machines. I have a whopping 18 new boxes to setup now, so I really need to get this little feature added which allows me to more easily add IP Addresses.

My function which generates the subnet based on the block number works fine, but I would like to be able to input something like 192.168.1.10/29 and have it add all 5 IP Addresses to the NIC. My function for adding the IP's works fine, but my question is...

Do I need to manually code it like this? (Obviously psuedo code and not a working example)

int 29block = 5
int 28block = 12

for (i = 0; i<29block; i++)
{
     string ip = ipinputbox.text;
     ip = ip + 2 + i; // 2 being the value to compensate for gateway/etc.
     AddIpAddress(ip);
}

enter image description here

2012-04-03 23:02
by NoName
What 5 addresses would be added for your example, 192.168.1.10/29 - mellamokb 2012-04-03 23:16
Here is one of our blocks 72.26.196.160/29. So .162 - .166 would be the addresses I needed to add to the NIC - NoName 2012-04-03 23:53
Since 72.26.196.160/29 includes as valid hosts all those in the range .161 to .166, how is the program to know the actual range should only include .162 to .166 - mellamokb 2012-04-03 23:55


0

I've whipped up a class that can interpret a subnet address and return an enumerable collection of the addresses represented by that subnet. So for example, the ip subnet 192.168.1.10/29 should return all the addresses after (and including) 192.168.1.10 that fall in the subnet represented by /29, which is mask 255.255.255.248. There are six valid hosts in this subnet, .9 to .14. So the list returned would be

192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14

Here is the sample code I'm using (in LINQPad): http://pastebin.com/d6EE2bpj, and the sample output generated by the test code:

==192.168.1.10/29==
192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
==72.26.196.160/29==
72.26.196.161
72.26.196.162
72.26.196.163
72.26.196.164
72.26.196.165
72.26.196.166

The code generates the bit mask on the fly based on the subnet size, so it should be completely generic for any starting ip address and any subnet size.

2012-04-04 00:04
by mellamokb
Excellent, thank you so much - NoName 2012-04-04 08:02
@BrettPowell: Just wanted to follow up, have you gotten a chance to use the code in production, and is it working as expected - mellamokb 2012-04-04 14:47
Ads