当前位置:网站首页>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;
}
边栏推荐
- Best practice | using Tencent cloud AI willingness to audit as the escort of telephone compliance
- Excusez - moi, l'exécution a été réussie lors de l'utilisation des données de puits SQL Flink à Kafka, mais il n'y a pas de nombre dans Kafka
- The meaning of variables starting with underscores in PHP
- 2022-7-6 Leetcode 977. Square of ordered array
- Leecode3. Longest substring without repeated characters
- Oracle advanced (V) schema solution
- 使用day.js让时间 (显示为几分钟前 几小时前 几天前 几个月前 )
- 3D Detection: 3D Box和点云 快速可视化
- Data refresh of recyclerview
- [daily training] 648 Word replacement
猜你喜欢

Redis can only cache? Too out!

Details of redis core data structure & new features of redis 6

Dry goods | summarize the linkage use of those vulnerability tools

XML文件的解析操作

.net core 关于redis的pipeline以及事务

高等數學---第八章多元函數微分學1

Help tenants

交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)

Vmware共享主机的有线网络IP地址
![SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1](/img/10/6de1ee8467b18ae03894a8d5ba95ff.png)
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
随机推荐
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)
Clickhouse (03) how to install and deploy Clickhouse
PostgreSQL array type, each splice
XML文件的解析操作
648. Word replacement: the classic application of dictionary tree
Battle Atlas: 12 scenarios detailing the requirements for container safety construction
Transferring files between VMware and host
call undefined function openssl_ cipher_ iv_ length
Excuse me, I have three partitions in Kafka, and the flinksql task has written the join operation. How can I give the join operation alone
Wired network IP address of VMware shared host
作战图鉴:12大场景详述容器安全建设要求
【面试高频题】难度 2.5/5,简单结合 DFS 的 Trie 模板级运用题
Realize the IP address home display function and number home query
Laravel Form-builder使用
Indoor ROS robot navigation commissioning record (experience in selecting expansion radius)
为租客提供帮助
Beginner XML
"New red flag Cup" desktop application creativity competition 2022
What parameters need to be reconfigured to replace the new radar of ROS robot
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf