Fuppetia
Fuppetia

Reputation: 47

C# ip to hex to decimal

I need to read computers ip adress, which is already done. After that I need to change the recieved ip value to hex and then to decimal, basically like this

127.0.0.1 flip the value to 1.0.0.127 to hex 0100007F and finally to 16777343.

public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {

                string hexValue = ip.ToString();
                string cleanAmount = hexValue.Replace(".", string.Empty);
                Console.Write(cleanAmount + "\n");
                return ip.ToString();
            }
        }
        throw new Exception("No network adapters with an IPv4 address in the system!");
    }


    static void Main(string[] args)
    {
        GetLocalIPAddress();
    }

Upvotes: 0

Views: 1153

Answers (5)

Michał Turczyn
Michał Turczyn

Reputation: 37460

Try this:

string ipAddress = "127.0.0.1";
string[] parts = ipAddress.Split('.');
string hexResult = "";
// loop backwards, to reverese order of parts of IP
for (int i = parts.Length - 1; i >= 0; i--)
    hexResult += int.Parse(parts[i]).ToString("X").PadLeft(2, '0');
int finalResult = Convert.ToInt32(hexResult, 16);

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81563

It depends why you want this reversed, and if this is an endian issue

essentially you just need to return your int

BitConverter.ToInt64(IPAddress.Parse("127.0.0.1").GetAddressBytes(), 0);

Or a more verbose example

var bytes = IPAddress.Parse("127.0.0.1").GetAddressBytes();

if (!BitConverter.IsLittleEndian)
   Array.Reverse(bytes);

for (int i = 0; i < bytes.Length; i++)
    Console.Write(bytes[i].ToString("X2"));

Console.WriteLine("");

long r = BitConverter.ToInt32(bytes, 0);
Console.WriteLine(r);

Output

7F000001 
16777343

Full Demo Here

Upvotes: 0

Rafalon
Rafalon

Reputation: 4515

Why do you want to reverse anything at all?
You could just read each group and multiply its value by 256^rank:

static void Main()
{
    string ip = "127.0.0.1";

    string[] splitted = ip.Split('.');

    int value = 0;
    int factor = 1;

    for(int i=0;i<splitted.Length;i++)
    {
        value += factor*Convert.ToInt32(splitted[i]);
        factor*=256;
    }

    Console.WriteLine(value);
}

Writes 16777343.

Upvotes: 0

fubo
fubo

Reputation: 46007

Here you go

string input = "127.0.0.1";
string hex = string.Concat(input.Split('.').Reverse().Select(x => int.Parse(x).ToString("X").PadLeft(2,'0'))); // 0100007F 
int result = Convert.ToInt32(hex, 16); //16777343

Upvotes: 4

Martin Zikmund
Martin Zikmund

Reputation: 39092

You can use Convert.ToString to convert an int from decimal to a different numeral system:

Convert.ToString(127, 16); //16 for hexadecimal

Upvotes: 0

Related Questions