Ali Ghaffari

Ali Ghaffari

  • 1.1k
  • 680
  • 28.5k

How to Convert a given ip Address into Hexadecimal

Apr 7 2017 10:19 AM
Hello!
Can you tell me, how to convert an ip address which is given by user into Hexadecimal?
like ip address is: 192.168.8.100
the Hexadecimal is value is: C0.A8.08.64
I also convert the give ip into binary, the code for conversion of ip address into binary is given below:
 
string givenip = ip_textBox.Text;
string[] words = ip_textBox.Text.Split('.');
int[] ipbroken = new int[4];
int ipoctetnumb = 0;
//getting hostname
IPHostEntry hostEntry = Dns.GetHostEntry(givenip);
textBox3.Text = hostEntry.HostName;
//removing dot from IP
foreach (var item in words)
{
if (item != ".")
{
ipbroken[ipoctetnumb] = Convert.ToInt32(item);
ipoctetnumb++;
}
}
//class information
if (ipbroken[0] == 0 || ipbroken[0] <= 126)
{
textBox6.Text = "Class A address ( 1.0.0.0 - 126.255.255.255 )\r\n 0nnnnnnn.hhhhhhhh.hhhhhhhh.hhhhhhhh";
}
else if (ipbroken[0] == 128 || ipbroken[0] <= 190)
{
textBox6.Text = "Class B address ( 128.0.0.0 - 191.255.255.255 )\r\n 10nnnnnn.nnnnnnnn.hhhhhhhh.hhhhhhhh";
}
else if (ipbroken[0] == 192 || ipbroken[0] <= 222)
{
textBox6.Text = "Class C address ( 192.0.0.0 - 223.255.255.255 )\r\n 110nnnnn.nnnnnn.nnnnnn.hhhhhhhhh";
}
//converted into Hexadecimal value
//Conversion into binary
string[] binaryip = new string[4];
for (int j = 0; j < 4; j++)
{
int quot;
string rem = "";
while (ipbroken[j] >= 1)
{
quot = ipbroken[j] / 2;
rem += (ipbroken[j] % 2).ToString();
ipbroken[j] = quot;
}
string bin = "";
for (int i = rem.Length - 1; i >= 0; i--)
{
bin = bin + rem[i];
}
int binIp;
if (bin.Length < 8)
{
binIp = 8 - bin.Length;
for (int i = 0; i < binIp; i++)
{
bin = "0" + bin;
}
}
binaryip[j] = bin;
}
textBox5.Text = binaryip[0] + "." + binaryip[1] + "." + binaryip[2] + "." + binaryip[3];
}
 

Answers (1)