Slothie
Slothie

Reputation: 59

Converting a char array to a IPv6 address in C#?

I have numbers stored in a SQL Server char(39) field that I need to convert to a IPv6 IPAddress?

Examples

281470698521600
281470698522623
58569107296622255421594597096899477504 
58569107375850417935858934690443427839

I don't know much about IPv6 but I'm assuming I can ping the address to verify it is correct. I could do with some help converting it from a number though? The examples seem short, are they missing subnetting?

Upvotes: 0

Views: 150

Answers (1)

jdweng
jdweng

Reputation: 34421

The number has to be made into a hex string (12 characters) and then separate the character into groups of 2 characters with a colon between each group. Here is sample code

string input = "281470698521600";
string hex = long.Parse(input).ToString("x");
string[] array = hex.ToCharArray()
    .Select((x, i) => new { chr = x, index = i })
    .GroupBy(x => x.index / 2)
    .Select(x => x.First().chr.ToString() + x.Last().chr.ToString())
    .ToArray();
string IPV6 = string.Join(":", array);

The output would be this : ff:ff:01:00:04:00

Upvotes: 1

Related Questions