当前位置:网站首页>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;
}
边栏推荐
- MySQL error 28 and solution
- 【日常训练】648. 单词替换
- [daily training -- Tencent select 50] 231 Power of 2
- 请问,PTS对数据库压测有好方案么?
- [high frequency interview questions] difficulty 2.5/5, simple combination of DFS trie template level application questions
- ES日志报错赏析-Limit of total fields
- The meaning of variables starting with underscores in PHP
- Seven propagation behaviors of transactions
- 实现IP地址归属地显示功能、号码归属地查询
- . Net core about redis pipeline and transactions
猜你喜欢
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
Build a secure and trusted computing platform based on Kunpeng's native security
Flink | multi stream conversion
2022-7-6 使用SIGURG来接受外带数据,不知道为什么打印不出来
供应链供需预估-[时间序列]
Xshell connection server changes key login to password login
Navicat运行sql文件导入数据不全或导入失败
[fortress machine] what is the difference between cloud fortress machine and ordinary fortress machine?
AI talent cultivation new ideas, this live broadcast has what you care about
MySQL error 28 and solution
随机推荐
Xshell connection server changes key login to password login
Leetcode simple question sharing (20)
Move base parameter analysis and experience summary
Transferring files between VMware and host
SSRF漏洞file伪协议之[网鼎杯 2018]Fakebook1
Drawerlayout suppress sideslip display
请问,在使用flink sql sink数据到kafka的时候出现执行成功,但是kafka里面没有数
move base参数解析及经验总结
Evolution of customer service hotline of dewu
请问,如图,pyhon云函数提示使用了 pymysql模块,这个是怎么回事?
【网络安全】sql注入语法汇总
Is the compass stock software reliable? Is it safe to trade stocks?
Data refresh of recyclerview
Supply chain supply and demand estimation - [time series]
LeetCode简单题分享(20)
Realization of search box effect [daily question]
属性关键字Aliases,Calculated,Cardinality,ClientName
MySQL error 28 and solution
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
FC连接数据库,一定要使用自定义域名才能在外面访问吗?