Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to get ipv4 last octet

Tags:

c#

ip-address

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

Ex.: 192.168.1.100

I want 100

Tks

like image 273
Alexandre Avatar asked Aug 03 '11 13:08

Alexandre


2 Answers

just for fun:

Console.WriteLine(IPAddress.Parse("192.168.1.33").GetAddressBytes()[3]);
like image 107
Rushui Guan Avatar answered Oct 24 '22 23:10

Rushui Guan


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;
}
like image 29
Jonathan Dickinson Avatar answered Oct 24 '22 22:10

Jonathan Dickinson