Murhaf Sousli
Murhaf Sousli

Reputation: 13296

How to trim IP Address to get the first 3 parts of it?

I need to trim a given IP Address to get the first 3 parts of it

Example:

"192.168.1.20" ➨ "192.168.1."
"29.6.60.241" ➨ "29.6.60."

Upvotes: 7

Views: 6923

Answers (5)

Max Keller
Max Keller

Reputation: 383

String result = input.Substring(0, input.LastIndexOf("."));

Upvotes: 15

Hans Kesting
Hans Kesting

Reputation: 39283

Using String.LastIndexOf(), it should be easy.

EDIT
Using that method you can locate the last '.'. Then you need a substring up to and (apparently) incuding that '.'. Something like:

string shortened = longIP.Substring(0,longIP.LastIndexOf(".")+1);

Upvotes: 5

Murhaf Sousli
Murhaf Sousli

Reputation: 13296

string sHostName = Dns.GetHostName();
IPHostEntry ipE = Dns.GetHostByName(sHostName);
IPAddress[] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
    if(IpA[i].AddressFamily == AddressFamily.InterNetwork)
    {
        Console.WriteLine("IP Address {0}: {1} {2} ", i, IpA[i].ToString() , sHostName);
        string[] x = IpA[i].ToString().Split('.');
        Console.WriteLine("{0}.{1}.{2}.", x[0], x[1], x[2]);
    }
}

Upvotes: 1

Ken Birman
Ken Birman

Reputation: 1118

Internally, IP addresses (IPv4 and IPv6) are just bit strings. IPv4 fits into 32 bits and IPv6 fits into 64 bits. So the real answer to your question is to just mask the bits you want to keep using a logical AND operation and have the others be 0.

In most situations you get to specify an IP address together with a mask. The rule is that to ask if A is the same as B, you check the bits for which the mask bit is true.

This leads to a common notation: people write an IP address like 124.51.3/17 to say that the first part describes an IP address (maybe IPv4) and that the /17 means that the first 17 bits are the ones to consider.

Upvotes: 0

John Koerner
John Koerner

Reputation: 38077

string ip= "192.168.1.100";
string partial = ip.Substring(0,ip.LastIndexOf("."));

Upvotes: 2

Related Questions