Reputation: 461
I have an IP "192.168.232.189" and I need to convert it to a hex value "C0A8E8BD" using c#. Can anyone help?
I saw this Converting IP Address to Hex but I'm not entirely sure how to implement that is c#
Thanks
Upvotes: 2
Views: 7042
Reputation: 45947
here you go
string ip = "192.168.232.189";
string hex = string.Concat(ip.Split('.').Select(x => byte.Parse(x).ToString("X2")));
.
with string.Split()
byte.Parse()
byte
to a hex string ToString("X2")
string.Concat()
Upvotes: 1
Reputation: 1633
Here is a solution for you. First convert the IP address to a number and then get its HEX value. You may want to reverse the HEX to IP, may be in the future, so this link is a Resource for IP conversions that I use. See output below.
public class Program
{
static void Main(string[] args)
{
string ip = "192.168.232.189";
string ipHexFormat = string.Format("{0:X}", ConvertIpToNumber(ip));
Console.WriteLine(ipHexFormat);
}
public static long ConvertIpToNumber(string dottedIpAddress)
{
long num = 0;
if (dottedIpAddress == "")
{
return 0;
}
else
{
int i = 0;
string[] splitIpAddress = dottedIpAddress.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
for (i = splitIpAddress.Length - 1; i >= 0; i--)
{
num += ((long.Parse(splitIpAddress[i]) % 256) * (long)Math.Pow(256, (3 - i)));
}
return num;
}
}
}
Upvotes: 1
Reputation: 186668
If IP address is represented as String
and you want to have a String
as a result you can
'.'
into IP address partsint
Possible implementation (Linq) is
String address = "192.168.232.189";
// "C0A8E8BD"
String result = String.Concat(address.Split('.').Select(x => int.Parse(x).ToString("X2")));
Upvotes: 2
Reputation: 912
You can use System.Net.IPAddress
IPAddress ip = IPAddress.Parse("192.168.232.189");
Console.WriteLine(ByteArrayToString(ip.GetAddressBytes()));
public static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-","");
}
Here is demo
Upvotes: 0
Reputation: 21
Each piece of the IP address is equivalent to 2 hex digits (or 8 binary digits). So your problem comes down to splitting up 192.168.232.189 to 192, 168, 232, 189. Then converting each piece (simple decimal-hex conversion) and putting it back together.
Upvotes: 2
Reputation: 111850
By using the IPAddress
class to parse the address (parsing is always the most complex part):
IPAddress address = IPAddress.Parse("192.168.232.189");
// Otherwise IPAddress would parse even IPv6 addresses
if (address.AddressFamily != AddressFamily.InterNetwork)
{
throw new ArgumentException("address");
}
byte[] bytes = address.GetAddressBytes();
string strAddress = string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", bytes[0], bytes[1], bytes[2], bytes[3]);
Upvotes: 2