IPv6: Add Method for conversion to/from byte[] (opt. including mask)

pull/2/head
Harald Wolff 2019-10-07 09:04:51 +02:00
parent 990c00132e
commit 3566b0788b
1 changed files with 40 additions and 18 deletions

View File

@ -44,14 +44,23 @@ namespace ln.types
public IPv6(byte[] bytes)
:this()
{
if (bytes.Length == 16)
{
for (int n = 0; n < 8; n++)
{
value[n] = (ushort)((bytes[(n << 1) + 0] << 8) | bytes[(n << 1) + 0]);
}
mask = 128;
} else if (bytes.Length == 4)
if (bytes.Length == 16)
{
for (int n = 0; n < 8; n++)
{
value[n] = (ushort)((bytes[(n << 1) + 0] << 8) | bytes[(n << 1) + 1]);
}
mask = 128;
}
else if (bytes.Length == 17)
{
for (int n = 0; n < 8; n++)
{
value[n] = (ushort)((bytes[(n << 1) + 0] << 8) | bytes[(n << 1) + 1]);
}
mask = bytes[16];
}
else if (bytes.Length == 4)
{
value[5] = 0xffff;
value[6] = (ushort)((bytes[0] << 8) | bytes[1]);
@ -90,18 +99,31 @@ namespace ln.types
return Network.Equals(ipNetwork);
}
public byte[] ToBytes()
{
byte[] bytes = new byte[16];
public byte[] ToBytes()
{
byte[] bytes = new byte[16];
for (int n = 0; n < 8; n++)
{
bytes[(n << 1) + 1] = (byte)((value[n] >> 0) & 0xff);
bytes[(n << 1) + 0] = (byte)((value[n] >> 8) & 0xff);
}
for (int n = 0; n < 8; n++)
{
bytes[(n << 1) + 1] = (byte)((value[n] >> 0) & 0xff);
bytes[(n << 1) + 0] = (byte)((value[n] >> 8) & 0xff);
}
return bytes;
}
return bytes;
}
public byte[] ToCIDRBytes()
{
byte[] bytes = new byte[17];
for (int n = 0; n < 8; n++)
{
bytes[(n << 1) + 1] = (byte)((value[n] >> 0) & 0xff);
bytes[(n << 1) + 0] = (byte)((value[n] >> 8) & 0xff);
}
bytes[16] = mask.GetBytes()[0];
return bytes;
}
public IEnumerable<IPv6> Split(int splitWidth)
{