2012-03-16 32 views
5

我需要修剪給定的ip地址來獲取它的第3個部分如何修改IP地址字符串以獲取其前3個部分?

,如: 「192.168.1。」

「192.168.1.20」 ➨
「29.6.60.241」「29.6.60」。

在此先感謝。

+2

IPv6地址如何? – 2012-03-16 13:11:59

+0

@ Mr.Disappointment,你的別名在你的評論之前:D – 2012-03-16 13:21:21

回答

11

String result = input.substring(0,input.lastIndexOf("."));

+0

謝謝:) String result = input.substring(0,input.lastIndexOf(「。」))+「。」; – 2012-03-18 13:04:44

5

使用String.LastIndexOf(),應該很容易。

編輯
使用該方法可以找到最後一個'。'。然後你需要一個子串直到(顯然)包含'。'。喜歡的東西:

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

如果他需要包含'.',那麼應該是'lastIndexOf' + 1? – 2012-03-16 13:35:42

+0

@ Moo-Juice - 你是對的,更新 – 2012-03-16 14:06:24

2
string ip= "192.168.1.100"; 
string partial = ip.Substring(0,ip.LastIndexOf(".")); 
0
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]); 
    } 
} 
+0

@ Mr.Disappointment是的你對我忘了它..我編輯了答案 – 2012-03-16 13:27:21

0

內部,IP地址(IPv4和IPv6)的剛咬弦。 IPv4適合32位,IPv6適合64位。所以你的問題的真正答案是掩蓋你想要保持使用邏輯與操作,並讓其他人爲0的位。

在大多數情況下,你可以指定一個IP地址連同掩碼。規則是詢問A是否與B相同,檢查掩碼位爲真的位。

這導致了一種常見的表示方式:人們編寫一個類似於124.51.3/17的IP地址來表示第一部分描述了一個IP地址(可能是IPv4),並且/ 17表示前17位是考慮。