当前位置:网站首页>IP address home location query full version
IP address home location query full version
2022-07-07 14:04:00 【It is small new】
package controller;
import java.util.Scanner;
import manager.DataProcessManager;
public class SystemController {
@SuppressWarnings("resource")
public static void main(String[] args) {
// Receive user input
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println(" Please enter IP Address : ");
String ip = scanner.nextLine();
// Inquire about
long startTime = System.currentTimeMillis();
String location = DataProcessManager.getLocation(ip);
long endTime = System.currentTimeMillis();
System.out.println(" Total time : " + (endTime - startTime) + " "
+ location);
}
}
}
package manager;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pojo.IPAndLocationPojo;
import utli.FileOperatorUtil;
import utli.IPUtil;
import utli.RegexUtil;
import utli.SerDeUtil;
import utli.StaticValue;
/**
* Program core business class
*
*/
public class DataProcessManager {
private static IPAndLocationPojo[] ipAndLocationPojoArray = null;
static {
// Save data object
List<IPAndLocationPojo> ipAndLocationPojos = null;
// Determine whether there is a serialized file
File file = new File(StaticValue.serdeObiFilePath);
if (file.exists()) {
// TODO
long startTime = System.currentTimeMillis();
// If there is Just deserialize
try {
Object obj = SerDeUtil.getObj(StaticValue.serdeObiFilePath,
StaticValue.cacheByteArrayLength);
ipAndLocationPojoArray = (IPAndLocationPojo[]) obj;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(" Deserialization , Time consuming : " + (endTime - startTime));
} else {
// non-existent Just read the data And structured Sort then serialize
try {
// get data
ipAndLocationPojos = DataProcessManager.getPojoList(
StaticValue.ipLibrayPath, StaticValue.encoding);
// Turn the array and sort
// TODO
long startTime = System.currentTimeMillis();
ipAndLocationPojoArray = DataProcessManager
.convertListToArraySort(ipAndLocationPojos);
// serialize
SerDeUtil.saveObj(ipAndLocationPojoArray,
StaticValue.serdeObiFilePath,
StaticValue.cacheByteArrayLength);
long endTime = System.currentTimeMillis();
System.out.println(" Turn array and sort serialization , Time consuming : " + (endTime - startTime));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* External interface , Participation is IP, The exit is the place of belonging
*
* @param ip
* @return
*/
public static String getLocation(String ip) {
// check IP
if (!RegexUtil.isValidIP(ip)) {
return " Please enter the correct IP Address ";
}
// Binary search
int index = DataProcessManager.binaraySeach(ipAndLocationPojoArray, ip);
// Determine if it is found
if (index == -1) {
return null;
} else {
return ipAndLocationPojoArray[index].getLocation();
}
}
/**
* Binary search , Participation is IP And an array , The output parameter is the corresponding index , No return found -1
*
* @param ipAndLocationPojoArray
* @param targetIP
* @return
* @throws IOException
*/
private static int binaraySeach(IPAndLocationPojo[] ipAndLocationPojoArray,
String targetIP) {
// hold IP Convert to long
long targetIPLong = IPUtil.ipToLong(targetIP);
int startIndex = 0;
int endIndex = ipAndLocationPojoArray.length - 1;
int m = (startIndex + endIndex) / 2;
/**
* If Less than start IP Find the front
*
* If Greater than end IP Find the back
*
* If Greater than or equal to start IP And Less than or equal to end IP It says it found it
*/
while (startIndex <= endIndex) {
if (targetIPLong >= ipAndLocationPojoArray[m].getStartIPLong()
&& targetIPLong <= ipAndLocationPojoArray[m].getEndIPLong()) {
return m;
}
if (targetIPLong < ipAndLocationPojoArray[m].getStartIPLong()) {
endIndex = m - 1;
} else {
startIndex = m + 1;
}
m = (startIndex + endIndex) / 2;
}
return -1;
}
/**
* Convert the set into an array and sort
*
* @param ipAndLocationPojos
* @return
*/
private static IPAndLocationPojo[] convertListToArraySort(
List<IPAndLocationPojo> ipAndLocationPojos) {
// Create array
IPAndLocationPojo[] ipAndLocationPojoArray = new IPAndLocationPojo[ipAndLocationPojos
.size()];
// Convert to array
ipAndLocationPojos.toArray(ipAndLocationPojoArray);
// Sort
Arrays.sort(ipAndLocationPojoArray);
return ipAndLocationPojoArray;
}
/**
* Structured data collection
*
* @param filePath
* @param encoding
* @return
* @throws IOException
*/
private static List<IPAndLocationPojo> getPojoList(String filePath,
String encoding) throws IOException {
// Save data object
List<IPAndLocationPojo> ipAndLocationPojos = new ArrayList<IPAndLocationPojo>();
// TODO
long startTime = System.currentTimeMillis();
List<String> lineList = FileOperatorUtil
.getLineList(filePath, encoding);
long endTime = System.currentTimeMillis();
System.out.println(" Reading data , Time consuming : " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (String string : lineList) {
// Judge whether it is an empty line
if (string == null || string.trim().equals("")) {
continue;
}
// Split into arrays
String[] columnArray = string.split(" ");
// Get start IP
String startIP = columnArray[0];
// End of acquisition IP
String endIP = columnArray[1];
// Get the place of belonging
String location = columnArray[2];
// Encapsulate into objects
IPAndLocationPojo ipAndLocationPojo = new IPAndLocationPojo(
startIP, endIP, location);
// Add to collection
ipAndLocationPojos.add(ipAndLocationPojo);
}
endTime = System.currentTimeMillis();
System.out.println(" Structured data , Time consuming : " + (endTime - startTime));
return ipAndLocationPojos;
}
}
package pojo;
import java.io.Serializable;
import utli.IPUtil;
public class IPAndLocationPojo {
private static final long serialVersionUID = 1L;
// Derived fields , Used to hold IP Corresponding long value
private long startIPLong;
private long endIPLong;
/**
* start IP
*/
private transient String startIP;
/**
* end IP
*/
private transient String endIP;
/**
* Place of ownership
*/
private String location;
public int compareTo(IPAndLocationPojo o) {
long status = this.startIPLong - o.startIPLong;
// Cannot cast , If the two values differ 2147483647 Words , Convert to int after Get a negative number
// return (int) (this.startIPLong - o.startIPLong);
return status > 0 ? 1 : 0;
}
public String getStartIP() {
return startIP;
}
public long getStartIPLong() {
return startIPLong;
}
public void setStartIPLong(long startIPLong) {
this.startIPLong = startIPLong;
}
public long getEndIPLong() {
return endIPLong;
}
public void setEndIPLong(long endIPLong) {
this.endIPLong = endIPLong;
}
public void setStartIP(String startIP) {
this.startIP = startIP;
}
public String getEndIP() {
return endIP;
}
public void setEndIP(String endIP) {
this.endIP = endIP;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public IPAndLocationPojo(String startIP, String endIP, String location) {
super();
this.startIP = startIP;
this.endIP = endIP;
this.location = location;
// Assign a value to a long integer
this.startIPLong = IPUtil.ipToLong(startIP);
this.endIPLong = IPUtil.ipToLong(endIP);
}
public IPAndLocationPojo() {
super();
}
@Override
public String toString() {
return "IPAndLocationPojo [startIP=" + startIP + ", endIP=" + endIP
+ ", location=" + location + "]";
}
}
package utli;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class FileOperatorUtil {
/**
* Read the file and return list aggregate
*
* @param filePath
* File path
* @param encoding
* Character encoding
* @return
* @throws IOException
*/
public static List<String> getLineList(String filePath, String encoding)
throws IOException {
// 2 Node stream docking file
FileInputStream fis = new FileInputStream(filePath);
// 3 Convert to character stream and specify character encoding
Reader reader = new InputStreamReader(fis, encoding);
// 4 Buffering streams improves efficiency
BufferedReader br = new BufferedReader(reader);
// 5 Read
String line = null;
// Save the read data
List<String> lineList = new ArrayList<String>();
while ((line = br.readLine()) != null) {
// Add to collection
lineList.add(line);
}
// 6 close
br.close();
return lineList;
}
}
package utli;
public class IPUtil {
public static void main(String[] args) {
String ip = "126.56.78.59";
long ipLong = ipToLong(ip);
System.out.println(ipLong);
System.out.println(longToIP(ipLong));
}
/**
* take 127.0.0.1 Formal IP The address is converted to a decimal integer , There is no error handling here
* By shifting left (<<) Weight the numbers in each paragraph , The power of the first paragraph is 2 Of 24 Power , The power of the second paragraph is 2 Of 16 Power , The power of the third paragraph is 2 Of 8 Power , The right of the last paragraph is 1
*/
public static long ipToLong(String ipaddress) {
long[] ip = new long[4];
// First find IP In the address string . The location of
int position1 = ipaddress.indexOf(".");
int position2 = ipaddress.indexOf(".", position1 + 1);
int position3 = ipaddress.indexOf(".", position2 + 1);
// Each one . Convert strings between to integers
ip[0] = Long.parseLong(ipaddress.substring(0, position1));
ip[1] = Long.parseLong(ipaddress.substring(position1 + 1, position2));
ip[2] = Long.parseLong(ipaddress.substring(position2 + 1, position3));
ip[3] = Long.parseLong(ipaddress.substring(position3 + 1));
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
/**
* Convert integer to decimal form 127.0.0.1 Formal ip Address Shift the integer value to the right (>>>), Move right 24 position , When moving to the right, the high position makes up 0, The number obtained is the first paragraph IP.
* Through the and operator (&) Set the high of the integer value 8 Set as 0, Move right again 16 position , The number obtained is the second paragraph IP.
* The high of the integer value through the and operator 16 Set as 0, Move right again 8 position , The number obtained is the third paragraph IP. The high of the integer value through the and operator 24 Set as 0, The figure obtained is the fourth paragraph IP.
*/
public static String longToIP(long ipaddress) {
StringBuffer sb = new StringBuffer("");
// Move right directly 24 position
sb.append(String.valueOf((ipaddress >>> 24)));
sb.append(".");
// Will be high 8 Location 0, And then move right 16 position
sb.append(String.valueOf((ipaddress & 0x00FFFFFF) >>> 16));
sb.append(".");
// Will be high 16 Location 0, And then move right 8 position
sb.append(String.valueOf((ipaddress & 0x0000FFFF) >>> 8));
sb.append(".");
// Will be high 24 Location 0
sb.append(String.valueOf((ipaddress & 0x000000FF)));
return sb.toString();
}
}
package utli;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Regular expression tool class
*
*
*/
public class RegexUtil {
/**
* check IP
*
*/
public static boolean isValidIP(String input){
String regex="(?=(\\b|\\D))(((\\d{1,2})|(1\\d{1,2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{1,2})|(2[0-4]\\d)|(25[0-5]))(?=(\\b|\\D))";
return isValid(regex,input);
}
/**
* format checks Whole word matching
*
*/
public static boolean isValid(String regex,String input){
// Create engine objects
Pattern pattern=Pattern.compile(regex);
// Create matchers
Matcher matcher=pattern.matcher(input);
return matcher.matches();
}
}
package utli;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Serialize related tool classes
*
*
*/
public class SerDeUtil {
/**
* serialize
*/
public static void saveObj(Object obj,String filePath,int cacheByteArrayLength)throws IOException{
//1 serialize
FileOutputStream fos=new FileOutputStream(filePath);
// Byte array stream
ByteArrayOutputStream baos=new ByteArrayOutputStream(cacheByteArrayLength);
// Write out the data to the byte array
oos.writeObject(obj);
// Convert to byte array
byte[]byteArray=baos.toByteArray();
oos.flush();
oos.close();
fos.write(byteArray);
fos.close();
}
/**
* Deserialization
*/
public static Object getObj(String filePath,int cacheByteArrayLength)throws IOException,ClassNotFoundException{
//2 Deserialization
FileInputStream fis=new FileInputStream(filePath);
byte[]byteArray=new byte[cacheByteArrayLength];
// Data is read into byte array
fis.read(byteArray);
fis.close();
// Byte array buffer stream
ByteArrayInputStream bais=new ByteArrayInputStream(byteArray);
ObjectInputStream ois=new ObjectInputStream(bais);
Object obj=ois.readObject();
ois.close();
return obj;
}
}
package utli;
/**
* Static variables in a set
*
*
*/
public class StaticValue {
// File name after serialization
public static String serdeObiFilePath="ipLibObj.data";
// Address library file path
public static String ipLibrayPath="ip_location_relation.txt";
// Character encoding
public static String encoding="UTF-8";
// Serialized file size
public static int cacheByteArrayLength=25*1024*1024;
}
边栏推荐
- Environment configuration
- requires php ~7.1 -&gt; your PHP version (7.0.18) does not satisfy that requirement
- The delivery efficiency is increased by 52 times, and the operation efficiency is increased by 10 times. See the compilation of practical cases of financial cloud native technology (with download)
- How can the PC page call QQ for online chat?
- js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
- How to check the ram and ROM usage of MCU through Keil
- Use day JS let time (displayed as minutes, hours, days, months, and so on)
- AutoCAD - how to input angle dimensions and CAD diameter symbols greater than 180 degrees?
- 【网络安全】sql注入语法汇总
- 《厌女:日本的女性嫌恶》摘录
猜你喜欢
2022-7-6 Leetcode27. Remove the element - I haven't done the problem for a long time. It's such an embarrassing day for double pointers
C语言数组相关问题深度理解
AI人才培育新思路,这场直播有你关心的
Mathématiques avancées - - chapitre 8 différenciation des fonctions multivariables 1
2022-7-6 Leetcode 977. Square of ordered array
Supply chain supply and demand estimation - [time series]
高等數學---第八章多元函數微分學1
带你掌握三层架构(建议收藏)
Social responsibility · value co creation, Zhongguancun network security and Information Industry Alliance dialogue, wechat entrepreneur Haitai Fangyuan, chairman Mr. Jiang Haizhou
Dry goods | summarize the linkage use of those vulnerability tools
随机推荐
Transferring files between VMware and host
"Song of ice and fire" in the eleventh issue of "open source Roundtable" -- how to balance the natural contradiction between open source and security?
THINKPHP框架的优秀开源系统推荐
Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
请问,如图,pyhon云函数提示使用了 pymysql模块,这个是怎么回事?
带你掌握三层架构(建议收藏)
.net core 关于redis的pipeline以及事务
How does MySQL control the number of replace?
648. Word replacement: the classic application of dictionary tree
2022-7-6 Leetcode 977.有序数组的平方
请问,redis没有消费消息,都在redis里堆着是怎么回事?用的是cerely 。
2022-7-6 sigurg is used to receive external data. I don't know why it can't be printed out
Help tenants
PC端页面如何调用QQ进行在线聊天?
PHP中用下划线开头的变量含义
内存溢出和内存泄漏的区别
手里的闲钱是炒股票还是买理财产品好?
Vmware共享主机的有线网络IP地址
Deep understanding of array related problems in C language
Oracle advanced (V) schema solution