Use the binary search to determine the IP region range test, ip Region

Source: Internet
Author: User

Use the binary search to determine the IP region range test, ip Region

All IP addresses are converted to the Long type. Each region is represented by an IP segment and the IP segment is determined by a binary search.





Package hello;

Import java. util .*;


Public class datatest {


Public static void main (String [] args) throws InterruptedException {
Final HashMap <Integer, String> map = new HashMap <Integer, String> ();
Final String DELIMITER = "\ t ";
String line = ("1677721616777471 Australia ");
String [] str = line. split (DELIMITER );
Integer key_begin = Integer. parseInt (str [0]. trim ());
Integer key_end = Integer. parseInt (str [1]. trim ());
String country = str [2]. trim ();
// System. out. println (key_begin + "" + "" + country );
Map. put (key_begin, country );
ArrayList <Integer> list = new ArrayList <Integer> ();
Integer ip = 16777473;


List. add (1, 16777216 );
List. add (1, 16777472 );
List. add (1, 16778240 );
List. add (1, 16779264 );
List. add (1, 16777471 );
List. add (1, 16778239 );
List. add (1, 16779263 );
List. add (1, 16781311 );
Collections. sort (list );
System. out. println (list. toString ());


// [16777216,167 77471, 16777472,167 78239, 16778240,167 79263, 16779264,167 81311]
Int low = 0;
Int high = list. size ();
Int middle;
Int value;
While (low <= high ){
Middle = (low + high)/2;
Value = list. get (middle );
System. out. println ("middle =" + middle + "and value =" + value );
Thread. sleep (300 );
If (ip <list. get (middle )){
High = middle-1;
} Else if (ip> list. get (middle )){
Low = middle + 1;
System. out. println (high + "" + low );
Thread. sleep (300 );
}
} System. out. println (high + "" + list. get (high ));
}
}

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.