Best approach to get ipv4 last octet
I know substring can handle this but, is there a better way to get last octet from an IP ?
Ex开发者_Python百科.: 192.168.1.100
I want 100
Tks
just for fun:
Console.WriteLine(IPAddress.Parse("192.168.1.33").GetAddressBytes()[3]);
Just for fun I wrote the version which would have the least overhead (string manipulation etc.). @rushui has the correct answer though.
static void Main(string[] args)
{
Console.WriteLine(OctetInIP("10.1.1.100", 0));
Console.ReadLine();
}
static byte OctetInIP(string ip, int octet)
{
var octCount = 0;
var result = 0;
// Loop through each character.
for (var i = 0; i < ip.Length; i++)
{
var c = ip[i];
// If we hit a full stop.
if (c == '.')
{
// Return the value if we are on the correct octet.
if (octCount == octet)
return (byte)result;
octCount++;
}
else if (octCount == octet)
{
// Convert the current octet to a number.
result *= 10;
switch (c)
{
case '0': break;
case '1': result += 1; break;
case '2': result += 2; break;
case '3': result += 3; break;
case '4': result += 4; break;
case '5': result += 5; break;
case '6': result += 6; break;
case '7': result += 7; break;
case '8': result += 8; break;
case '9': result += 9; break;
default:
throw new FormatException();
}
if (result > 255)
throw new FormatException();
}
}
if (octCount != octet)
throw new FormatException();
return (byte)result;
}
It may be overkill, but a simple regex would also do the trick:
(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})
Remember what an IP address is, it is a 32-bit (4 byte) number. So masking the address with the subnet mask would actually be the correct way to do it. If you always want a subnet mask of 255.255.255.0, as your question implies, you can & the number with 0xFF to get the number.
But, if you don't care about efficiency, and only have the address as a string, the split on "." is just fine... :)
精彩评论