Find the address class and address type from the IP address with Java

【Overview】

The following information is displayed from the IP address specified by the argument (only one). ・ Address class (class A or class B or class C or class D) -Global IP address or private IP address

It is uploaded on GitHub. → ipAddressInfo I haven't tested it so much, so there may be miscoding ... If you find something wrong with the code or an improvement, please let us know in the comments or edit request.

【code】

Main.java


package pk;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

	private static final String CLASS_A_PREFIX = "0";
	private static final String CLASS_B_PREFIX = "10";
	private static final String CLASS_C_PREFIX = "110";
	private static final String CLASS_D_PREFIX = "1110";

	public static void main(String[] args) {
		//Argument check
		if (args.length != 1) {
			System.out.println("Specify the IP address in the argument.");
			System.exit(1);
		}

		//Regular expression for IP address determination
		Pattern pattern = Pattern.compile(
				"(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])");
		Matcher matcher = pattern.matcher(args[0]);

		if (matcher.find()) {
			List<String> addressList = new ArrayList<>();
			addressList = Arrays.asList(args[0].split("\\."));
			String addressClass = getIpAdressClass(getBinaryAddress(addressList.get(0)));

			switch (addressClass) {
				case CLASS_A_PREFIX:
					if (isPrivateAddress(addressList, CLASS_A_PREFIX)) {
						showResult("Class A", "Private IP address");
					} else {
						showResult("Class A", "Global IP address");
					}
					break;
				case CLASS_B_PREFIX:
					if (isPrivateAddress(addressList, CLASS_B_PREFIX)) {
						showResult("Class B", "Private IP address");
					} else {
						showResult("Class B", "Global IP address");
					}
					break;
				case CLASS_C_PREFIX:
					if (isPrivateAddress(addressList, CLASS_C_PREFIX)) {
						showResult("Class C", "Private IP address");
					} else {
						showResult("Class C", "Global IP address");
					}
					break;
				case CLASS_D_PREFIX:
					System.out.println("Class D.");
					break;
				default:
					System.out.println("An address that does not belong to any class.");
					break;
			}
		} else {
			System.out.println("It does not follow the IP address format.");
			System.exit(1);
		}
	}

	/**
	 *Convert from decimal to binary
	 * @param decimalAddress Decimal address
	 * @return Decimal number converted to binary number
	 */
	private static String getBinaryAddress(String decimalAddress) {
		return String.format("%8s", Integer.toBinaryString(Integer.valueOf(decimalAddress))).replace(" ", "0");
	}

	/**
	 *Determine which class it belongs to
	 * @param binaryAddress Binary address
	 * @Prefix for each return class, if it does not belong to any class"1"return it
	 */
	private static String getIpAdressClass(String binaryAddress) {
		if (CLASS_A_PREFIX.equals(binaryAddress.substring(0, 1))) {
			return CLASS_A_PREFIX;
		} else if (CLASS_B_PREFIX.equals(binaryAddress.substring(0, 2))) {
			return CLASS_B_PREFIX;
		} else if (CLASS_C_PREFIX.equals(binaryAddress.substring(0, 3))) {
			return CLASS_C_PREFIX;
		} else if (CLASS_D_PREFIX.equals(binaryAddress.substring(0, 4))) {
			return CLASS_D_PREFIX;
		} else {
			return "1";
		}
	}

	/**
	 *Determine whether the IP address belonging to the address class from class A to class C is a global IP or a private IP
	 * @param classPrefix
	 * @return Returns true for private IP addresses, false otherwise
	 */
	private static boolean isPrivateAddress(List<String> addressList, String classPrefix) {
		int firstSet = Integer.valueOf(addressList.get(0));
		int secondSet = Integer.valueOf(addressList.get(1));

		switch (classPrefix) {
			case CLASS_A_PREFIX:
				//The range of class A private IP addresses is
				// 10.0.0.0 ~ 10.255.255.255
				if (firstSet == 10) {
					return true;
				}
				break;
			case CLASS_B_PREFIX:
				//The range of class B private IP addresses is
				// 172.16.0.0 ~ 172.31.255.255
				if (firstSet == 172 && (16 <= secondSet && secondSet <= 31)) {
					return true;
				}
				break;
			case CLASS_C_PREFIX:
				//The range of class C private IP addresses is
				// 192.168.0.0 ~ 192.168.255.255
				if (firstSet == 192 && secondSet == 168) {
					return true;
				}
				break;
			case CLASS_D_PREFIX:
				//Class D is for multicast, so there is no concept of global or private
				break;
			default:
				return false;
		}
		return false;
	}

	/**
	 *Display the IP address identification result
	 * @param addressClass IP address class name
	 * @param addressStatus Global IP address or private IP address
	 */
	private static void showResult(String addressClass, String addressStatus) {
		System.out.println(addressClass + "And" + addressStatus + "is.");
	}
}

[Execution example]

> java pk.Main 208.77.188.166
Class C and global IP address.

【reference】

IP Matching with Regular Expressions -Regexp Regular expression that lets you search for an IP address with Hidemaru IP Address-Wikipedia [2018 [Spring] [Autumn] Applied Information Engineer Passed Textbook (Information Processing Engineer Examination)](https://www.amazon.co.jp/%E5%B9%B3%E6%88%9030% E5% B9% B4% E5% BA% A6% E3% 80% 90% E6% 98% A5% E6% 9C% 9F% E3% 80% 91% E3% 80% 90% E7% A7% 8B% E6% 9C% 9F% E3% 80% 91% E5% BF% 9C% E7% 94% A8% E6% 83% 85% E5% A0% B1% E6% 8A% 80% E8% A1% 93% E8% 80% 85-% E5% 90% 88% E6% A0% BC% E6% 95% 99% E6% 9C% AC-% E6% 83% 85% E5% A0% B1% E5% 87% A6% E7% 90% 86% E6% 8A% 80% E8% A1% 93% E8% 80% 85% E8% A9% A6% E9% A8% 93-% E5% A4% A7% E6% BB% 9D-% E3% 81% BF% E3% 82% 84% E5% AD% 90 / dp / 4774193151 / ref = sr_1_2? Ie = UTF8 & qid = 1517733175 & sr = 8-2 & keywords =% E5% BF% 9C% E7% 94% A8% E6% 83% 85 % E5% A0% B1% E6% 8A% 80% E8% A1% 93% E8% 80% 85)

[Bonus corner]

I will take the application information qualification in April of this year. If you pass, you will get a reward from the company, so buy a suit and PS Vita!

Recommended Posts

Find the address class and address type from the IP address with Java
Find the address class and address type from the IP address with Java [No. 2 decoction]
Get country from IP address (Java)
Find the greatest common divisor and least common multiple with JAVA
[Java] How to convert from String to Path type and get the path
[Java] Get the date with the LocalDateTime class
<java> Split the address before and after the street address with a regular expression
[Java] Set the time from the browser with jsoup
Increment with the third argument of iterate method of Stream class added from Java9
Java class type field
Feel the basic type and reference type easily with ruby
Write ABNF in Java and pass the email address
Java language from the perspective of Kotlin and C #
[Java] Get the date 10 days later with the Calendar class
Feel the basic type and reference type easily with ruby 2
Prepare the environment for java11 and javaFx with Ubuntu 18.4
"TCP / IP JAVA network programming understood from the basics" Compiled with Eclipse. Debug with Wireshark.
JSON in Java and Jackson Part 1 Return JSON from the server
Difference between Java and JavaScript (how to find the average)
What is the LocalDateTime class? [Java beginner] -Date and time class-
Implement Java Interface in JRuby class and call it from Java
Set the date and time from the character string with POI
Java class definition and instantiation
Find out all timezone IDs supported by the Java TimeZone class
Correct the character code in Java and read from the URL
[Java] Check the difference between orElse and orElseGet with IntStream
I want to return a type different from the input element with Java8 StreamAPI reduce ()
Search and execute method by name from instance with processing (java)
Install the memcached plugin on MySQL and access it from Java
How to set the IP address and host name of CentOS8
I want to return to the previous screen with kotlin and java!
[Android, Java] Method to find the elapsed date from two dates
Read the first 4 bytes of the Java class file and output CAFEBABE
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
Read barometric pressure and temperature with Java from Raspberry Pi 3 & BMP180
Create a calendar from the Calendar class by specifying the year and month
[Gradle] Build a Java project with a configuration different from the convention
Create an immutable class with JAVA
Call Kotlin's sealed class from Java
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
Get TypeElement and TypeMirror from Class
Install Java and Tomcat with Ansible
Code Java from Emacs with Eclim
IP address interfered with Docker bridge
Use JDBC with Java and Scala.
StringBuffer and StringBuilder Class in Java
java (use class type for field)
Follow the link with Selenium (Java)
Output PDF and TIFF with Java 8
Work with Google Sheets from Java
The road from JavaScript to Java
Encrypt with Java and decrypt with C #
Consideration and coping with the fact that SSL communication errors are more likely to occur from Java 11
Declare a method that has a Java return value with the return value data type
[Java] Get Json from URL and handle it with standard API (javax.script)
Let's express the result of analyzing Java bytecode with a class diagram
Using Java with AWS Lambda-Implementation Tips-Get Instance Name from Reagion and Instance ID
[Java] Create a jar file with both compressed and uncompressed with the jar command
Activity transition with JAVA class refactoring and instance experimented on Android side
Specify the favorite IP of the host network with docker-compose and start it