zoukankan      html  css  js  c++  java
  • 计算连续的IP地址

    题目:要求计算连续的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。

    按照传统的解法可以这么做:

    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稍微改造一下,可以这么干:

    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

  • 相关阅读:
    Mybatis使用resultType实现一对一查询
    利用webSocket使网页和服务器通信
    hdu--1728--special bfs
    hdu--1429--状压bfs
    hdu--3006--不知为何wa
    hdu--3001--类似旅行商<tsp>
    hdu--2660--二维费用背包
    hdu--4632--dp
    hdu--4497--数论
    hdu--4496--并查集
  • 原文地址:https://www.cnblogs.com/guwei4037/p/3507963.html
Copyright © 2011-2022 走看看