Calculating consecutive IP addresses

Source: Internet
Author: User

Question: consecutive IP addresses must be calculated.

For example, if the starting IP address is 192.168.2.2 and the total number of IP addresses is 3, all required IP addresses are 192.168.2.2, 192.168.2.3, and 192.168.2.4. For another example, if the starting IP address is 192.168.2.253 and the total number of IP addresses is 5, all the required IP addresses are 192.168.2.253, 192.168.2.254, 192.168.2.255, 192.168.3.0, and 192.168.3.1.

This can be done according to the traditional solution:

Static void Main (string [] args) {string ip = "192.168.2.253"; // start IP int count = 5; // calculate the number of consecutive IP addresses 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 );}}

If we use linq for a slight transformation, we can do this:

Static void Main (string [] args) {string ip = "192.168.2.253"; // start IP int count = 5; // calculate the number of consecutive IP addresses 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 );}}
Answer:

192.168.2.253
192.168.2.254
192.168.2.255
192.168.3.0
192.168.3.1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.