Hello,
I want to control if an Ip address is private or not. So I want to split Ip address. How can I do that?
For example;
Ip: 192.168.1.2
How can I get only "192", or "168", or "1" ?
Thanks.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted May 31, 2011, 11:13 AM EDT
Posted May 31, 2011, 11:03 AM EDT
First convert your IPAddress into string do the substring...
string IPAddress = "192.168.1.2";
string result = IPAddress.Substring(0, IPAddress.IndexOf("."));
Hope this helps
Posted May 31, 2011, 11:17 AM EDT
IPHostEntry ipEntry = Dns.GetHostByName(Dns.GetHostName ());
IPAddress[] addr = ipEntry.AddressList;
IPAddress add = addr[0];
string tempIPAddress = add.ToString();
string[] splitString = new string[1];
splitString[0] = ".";
string[] result = tempIPAddress.Split(splitString, StringSplitOptions.None);
In the result string array you'll have all the data like .. 192,168,2,2...
Hope this helps you.
yokzuRank #5,421 · 300 reputationPosted May 31, 2011, 11:18 AM EDT
Muralidharan, when I wrote "0" on your code, its getting me "192.". But When I wrote "1" or "2", its getting me another reseults than expected. But thanks for your reply.
Posted May 31, 2011, 11:22 AM EDT
Here 0 is the startingIndex in the string...
Sam HobbsRank #108 · 20.5K reputationPosted May 31, 2011, 4:53 PM EDT
Note that IP addresses in the version 6 format are 128 bits; 16 bytes.
The following showed me "127 0 0 1":
IPHostEntry ipEntry = Dns.GetHostEntry("localhost");
Byte[] AddressBytes = ipEntry.AddressList[1].GetAddressBytes();
Console.WriteLine("{0} {1} {2} {3}", AddressBytes[0], AddressBytes[1], AddressBytes[2], AddressBytes[3]);