Pages

Wednesday, October 28, 2015

Obtinerea adresei IP in formatul standard dintr-un numar intreg

Calcularea adresei IP în formatul IPv4 dintr-un număr întreg pe o platforma little endian.


long IP = 3232679515;

byte[] bytes = new byte[4];


bytes[0] = (byte)((IP >> 0) & 0xFF);
bytes[1] = (byte)((IP >> 8) & 0xFF);
bytes[2] = (byte)((IP >> 16) & 0xFF);
bytes[3] = (byte)((IP >> 24) & 0xFF);

// all of the protocol layers in the TCP/IP suite are defined
// to be big endian
string ipText = bytes.Select(b => b.ToString())
 .Aggregate((ip, b) => (ip.Length == 0) ? b : ip + "." + b);

Console.WriteLine(ipText); // prints 91.198.174.192


Bineînțeles că nu trebuie să ne chinuim atât de mult să obținem o adresă IP dintr-un long. În .net există clasa IPAddress care reprezintă o adresa IP și furnizează diferite proprietăți și metode utile:


System.Net.IPAddress ip = new System.Net.IPAddress(3232679515);
Console.WriteLine(ip.ToString()); // prints 91.198.174.192


Am citit despre:
Big-Endian vs. Little Endian: Endianness Explained, http://www.barrgroup.com/Embedded-Systems/How-To/Big-Endian-Little-Endian


Referințe:
MSDN, https://msdn.microsoft.com/en-us/library/system.net.ipaddress(v=vs.110).aspx
Understanding IP Addresses, Subnets, and CIDR Notation for Networking, https://www.digitalocean.com/community/tutorials/understanding-ip-addresses-subnets-and-cidr-notation-for-networking

No comments: