您好,登錄后才能下訂單哦!
題目:要求計(jì)算連續(xù)的IP地址。
舉例:起始IP為192.168.2.2,IP總個(gè)數(shù)為3,那么要求得的所有IP的為192.168.2.2,192.168.2.3,192.168.2.4。再舉個(gè)例子,起始IP為192.168.2.253,IP總個(gè)數(shù)為5那么要求得的所有IP為192.168.2.253,192.168.2.254,192.168.2.255,192.168.3.0,192.168.3.1。
按照傳統(tǒng)的解法可以這么做:
static void Main(string[] args) { string ip = "192.168.2.253";//起始IP int count = 5;//要計(jì)算連續(xù)IP的個(gè)數(shù) var ipValue = BitConverter.ToUInt32(IPAddress.Parse(ip).GetAddressBytes().Reverse().ToArray(), 0); for (uint i = 0; i < count; i++) { IPAddress newIp = IPAddress.Parse((ipValue + i).ToString()); Console.WriteLine(newIp); } }
那如果我們用linq稍微改造一下,可以這么干:
static void Main(string[] args) { string ip = "192.168.2.253";//起始IP int count = 5;//要計(jì)算連續(xù)IP的個(gè)數(shù) var ipValue = BitConverter.ToUInt32(IPAddress.Parse(ip).GetAddressBytes().Reverse().ToArray(), 0); var newIps = from p in Enumerable.Range(0, count) let newIp = ipValue + p select new { IP = IPAddress.Parse(newIp.ToString()) }; foreach (var newIp in newIps) { Console.WriteLine(newIp.IP); } }
答案:
192.168.2.253
192.168.2.254
192.168.2.255
192.168.3.0
192.168.3.1
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。