method to determine whether an IP address is within a specified range

Source: Internet
Author: User

For example, given an IP segment: 127.0.0.1 ~ 127.0.0.255, we want to determine whether a given IP address is in this section, you can first convert the IP address to an integer, and then the integer comparison size is very easy.

For example:
127.0.0.1 = 2130706433
127.0.0.255 = 2130706687

Judge:
127.0.1.253 = 2130706941
Whether the integer size is directly compared within this range can be

To convert an IP address into an integer:

 Public Static LongIp2long (stringIP) {  string[] ipbytes; Doublenum =0; if(!string. IsNullOrEmpty (IP)) {ipbytes= IP. Split ('.');  for(inti = ipbytes.length-1; I >=0; i--) {num+= ((int. Parse (Ipbytes[i])% the) * MATH.POW ( the, (3-i))); }  }  return(Longnum;}

Determines whether a given IP address is within the specified range:

long start = IP2Long( "127.0.0.1" ); long end = IP2Long( "127.0.0.255" ); long ipAddress = IP2Long( "127.0.1.253" ); bool inRange = (ipAddress >= start && ipAddress <= end); if (inRange){   //IP Address fits within range! }

method to determine whether an IP address is within a specified range

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.