当前位置:网站首页>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;
}
边栏推荐
- PostgreSQL array type, each splice
- 3D Detection: 3D Box和点云 快速可视化
- Attribute keywords aliases, calculated, cardinality, ClientName
- Common response status codes
- 2022-7-7 Leetcode 34.在排序数组中查找元素的第一个和最后一个位置
- 云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
- Solve the cache breakdown problem
- requires php ~7.1 -&gt; your PHP version (7.0.18) does not satisfy that requirement
- Flask session forged hctf admin
- Custom thread pool rejection policy
猜你喜欢

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)

TPG x AIDU | AI leading talent recruitment plan in progress!

Help tenants

Help tenants

flask session伪造之hctf admin

Navicat运行sql文件导入数据不全或导入失败

为租客提供帮助

Battle Atlas: 12 scenarios detailing the requirements for container safety construction

Custom thread pool rejection policy

最长上升子序列模型 AcWing 1014. 登山
随机推荐
Is the spare money in your hand better to fry stocks or buy financial products?
The difference between memory overflow and memory leak
最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航
AI talent cultivation new ideas, this live broadcast has what you care about
请问,PTS对数据库压测有好方案么?
Laravel5 call to undefined function openssl cipher iv length() 报错 PHP7开启OpenSSL扩展失败
Vmware共享主机的有线网络IP地址
Dry goods | summarize the linkage use of those vulnerability tools
Navicat run SQL file import data incomplete or import failed
最长上升子序列模型 AcWing 1014. 登山
Is it safe to open an account online now? Which securities company should I choose to open an account online?
Regular expression integer positive integer some basic expressions
2022-7-7 Leetcode 34.在排序数组中查找元素的第一个和最后一个位置
[fortress machine] what is the difference between cloud fortress machine and ordinary fortress machine?
Es log error appreciation -limit of total fields
Lavarel之环境配置 .env
2022-7-7 Leetcode 844. Compare strings with backspace
数据库系统概论-第一章绪论【概念模型、层次模型和三级模式(外模式、模式、内模式)】
Thread pool reject policy best practices
2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array