How to use IPAddress and IPv4Mask to get a range of IP addresses?

I am trying to do the following in C # /. NET 2.0:

Given an IPAddress object (say 192.168.127.100) and another IPAddress object containing an IPv4Mask / subnet mask (say 255.255.248.0), I should be able to calculate the beginning and end of the IP address range.

(Yes, I am trying to execute a for-loop through a range of addresses in a subnet.)

Theoretically, I should have bitwise AND on IPAddress and SubnetMask to get IPStart. Then I should be able to perform bitwise XOR on IPStart and an inverted (NOT'd) SubnetMask to get an IPEnd.

The IPAddress object provides methods for outputting the address as "long" or "byte []" (an array of bytes).

Performing a bitwise operation on a long one (because it is signed?) Leads to invalid results. And I cannot perform bitwise operations on IPAddresses as an array of bytes.

EDIT-1: Well, looping through each byte in the array and executing the bitwise AND, NOT, and XOR (in each appropriate situation) get the correct results.

The next problem I am facing is that I cannot execute for-loop easily after converting byte [] arrays to UInt32 or long. So, the first value works correctly, but incrementing yint / long by one increases the iPaddress from 192.168.127.0 to 193.168.127.0. It seems that after the byte [] array is converted to uint / long, the byte order is reversed. Thus, there is no easy way to increase from IPStart to IPEnd.

Are there any suggestions?

+3
4

[] , [] . [] , ( , ), , , . , , - , . :

Address:   192.168.127.100       11000000.10101000.01111 111.01100100
Netmask:   255.255.248.0 = 21    11111111.11111111.11111 000.00000000
Wildcard:  0.0.7.255             00000000.00000000.00000 111.11111111
=>
Network:   192.168.120.0/21      11000000.10101000.01111 000.00000000
Broadcast: 192.168.127.255       11000000.10101000.01111 111.11111111
HostMin:   192.168.120.1         11000000.10101000.01111 000.00000001
HostMax:   192.168.127.254       11000000.10101000.01111 111.11111110
+3

BitConverter, uints.

:

uint address = BitConverter.ToUInt32(IPAddress.Parse("192.168.127.100").GetAddressBytes(), 0);
uint mask = BitConverter.ToUInt32(IPAddress.Parse("255.255.248.0").GetAddressBytes(), 0);
+2

You are on the right track. Just process each byte in the array separately.

+1
source

http://ipnetwork.codeplex.com/

Code example:

var network = IPNetwork.Parse("192.168.1.0/29");
var addresses = IPNetwork.ListIPAddress(network);

foreach (var ip in addresses) {
    Console.WriteLine("{0}", ip);
}
+1
source

Source: https://habr.com/ru/post/1710490/


All Articles