Как вычислить диапазон IP, когда IP-адрес и сетевая маска даны?

Что-то еще не упомянутое в документации Дельфи 2009:

директива $WARN теперь имеет 3-ю опцию ERROR в дополнение к НА и ПРОЧЬ. Таким образом, Вы можете иметь:

{$WARN IMPLICIT_STRING_CAST OFF} to disable the warning
{$WARN IMPLICIT_STRING_CAST ON} to enable warning
{$WARN IMPLICIT_STRING_CAST ERROR} to turn the warning into an error
36
задан Chris Weber 13 April 2011 в 15:43
поделиться

4 ответа

my good friend Alessandro have a nice post regarding bit operators in C#, you should read about it so you know what to do.

It's pretty easy. If you break down the IP given to you to binary, the network address is the ip address where all of the host bits (the 0's in the subnet mask) are 0,and the last address, the broadcast address, is where all the host bits are 1.

For example:

ip 192.168.33.72 mask 255.255.255.192

11111111.11111111.11111111.11000000 (subnet mask)
11000000.10101000.00100001.01001000 (ip address)

The bolded parts is the HOST bits (the rest are network bits). If you turn all the host bits to 0 on the IP, you get the first possible IP:

11000000.10101000.00100001.01000000 (192.168.33.64)

If you turn all the host bits to 1's, then you get the last possible IP (aka the broadcast address):

11000000.10101000.00100001.01111111 (192.168.33.127)

So for my example:

the network is "192.168.33.64/26":
Network address: 192.168.33.64
First usable: 192.168.33.65 (you can use the network address, but generally this is considered bad practice)
Last useable: 192.168.33.126
Broadcast address: 192.168.33.127
61
ответ дан 27 November 2019 в 05:17
поделиться

Я просто отправлю код:

IPAddress ip = new IPAddress(new byte[] { 192, 168, 0, 1 });
int bits = 25;

uint mask = ~(uint.MaxValue >> bits);

// Convert the IP address to bytes.
byte[] ipBytes = ip.GetAddressBytes();

// BitConverter gives bytes in opposite order to GetAddressBytes().
byte[] maskBytes = BitConverter.GetBytes(mask).Reverse().ToArray();

byte[] startIPBytes = new byte[ipBytes.Length];
byte[] endIPBytes = new byte[ipBytes.Length];

// Calculate the bytes of the start and end IP addresses.
for (int i = 0; i < ipBytes.Length; i++)
{
    startIPBytes[i] = (byte)(ipBytes[i] & maskBytes[i]);
    endIPBytes[i] = (byte)(ipBytes[i] | ~maskBytes[i]);
}

// Convert the bytes to IP addresses.
IPAddress startIP = new IPAddress(startIPBytes);
IPAddress endIP = new IPAddress(endIPBytes);
26
ответ дан 27 November 2019 в 05:17
поделиться

Invert mask (XOR with ones), AND it with IP. Add 1. This will be the starting range. OR IP with mask. This will be the ending range.

8
ответ дан 27 November 2019 в 05:17
поделиться

Возможно, вы уже знаете это, но чтобы убедиться, что вы все правильно поняли, посмотрите http://www.subnet-calculator.com/ - там вы можете увидеть, как биты представляют части адреса сети и хоста.

2
ответ дан 27 November 2019 в 05:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: