Best way to get the latest ipv4 octet

I know that a substring can handle this, but is there a better way to get the last octet from IP?

Example: 192.168.1.100

I want 100

Tks

+5
source share
4 answers

just for fun:

Console.WriteLine(IPAddress.Parse("192.168.1.33").GetAddressBytes()[3]);
+16
source

Just for fun, I wrote a version that would have the least overhead (string manipulation, etc.). @rushui has the correct answer.

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;
}
+1
source

, :

(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})
-1

Remember what an IP address is, it is a 32-bit (4 byte) number. So masking an address using a subnet mask would be the right way to do this. If you always want to get a subnet mask of 255.255.255.0, then, as your question suggests, you can get a number with 0xFF as well.

But, if you do not care about efficiency and only have the address as a string, divide by "." just fine ... :)

-1
source

All Articles