题目:要求计算连续的IP地址。
举例:起始IP为192.168.2.2,IP总个数为3,那么要求得的所有IP的为192.168.2.2,192.168.2.3,192.168.2.4。再举个例子,起始IP为192.168.2.253,IP总个数为5那么要求得的所有IP为192.168.2.253,192.168.2.254,192.168.2.255,192.168.3.0,192.168.3.1。
按照传统的解法可以这么做:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
static
void
Main(
string
[] args)
{
string
ip =
"192.168.2.253"
;
//起始IP
int
count = 5;
//要计算连续IP的个数
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稍微改造一下,可以这么干:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
static
void
Main(
string
[] args)
{
string
ip =
"192.168.2.253"
;
//起始IP
int
count = 5;
//要计算连续IP的个数
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
本文转自 guwei4037 51CTO博客,原文链接:http://blog.51cto.com/csharper/1348959