Home Java javaTutorial Java method to query DNS/IP address based on website address

Java method to query DNS/IP address based on website address

Dec 06, 2017 am 10:21 AM
java address Inquire

Requirements: Given a URL address, for example: http://www.cncounter.com/tools/shorturl.php, parse the corresponding IP address and port number.

Note: This article does not involve the underlying DNS protocol and directly uses the API provided by the Java platform for operation.

DNS is Domain Name Service, which is domain name service.

We know that the classes related to URLs in Java include java.net.URL and java.net.URI, etc., where URI is a resource locator, which may include protocols such as file:.

So here we use the URL class. The code to obtain the port number is as follows:

 /**
   * 获取端口号
   *
   * @param href 网址, ftp, http, nntp, ... 等等
   * @return
   * @throws IOException
   */
  public static int parsePort(String href) throws IOException {
    //
    URL url = new URL(href);
    // 端口号; 如果 href 中没有明确指定则为 -1
    int port = url.getPort();
    if (port < 0) {
      // 获取对应协议的默认端口号
      port = url.getDefaultPort();
    }
    return port;
  }
Copy after login

The URL class is a class that existed in the early days of Java. . The internal logic is relatively complex. If you are interested, you can view the relevant JDK implementation code yourself.

There are two methods to get the port number:

getPort() is to get the port number specified in the URL. If not specified, -1 is returned.

getDefaultPort() is to obtain the default port number corresponding to the protocol. For example, the default port number of the http protocol is 80, the default port number of the https protocol is 443, etc.

Then let’s look at the code to extract the Host part:

 /**
   * 获取Host部分
   *
   * @param href 网址, ftp, http, nntp, ... 等等
   * @return
   * @throws IOException
   */
  public static String parseHost(String href) throws IOException {
    //
    URL url = new URL(href);
    // 获取 host 部分
    String host = url.getHost();
    return host;
  }
Copy after login

Essentially, you can also directly intercept the Host through regular expressions or String, but If you encounter a complicated situation, it is not easy to handle, for example: a complex URL like https://yourname:passwd@gitee.com/mumu-osc/NiceFish.git.

After extracting the domain name, you can use the java.net.InetAddress class to find the IP address.

The code is as follows:

 /**
   * 根据域名(host)解析IP地址
   *
   * @param host 域名
   * @return
   * @throws IOException
   */
  public static String parseIp(String host) throws IOException {
    // 根据域名查找IP地址
    InetAddress inetAddress = InetAddress.getByName(host);
    // IP 地址
    String address = inetAddress.getHostAddress();
    return address;
  }
Copy after login

As you can see, we use the InetAddress.getByName() static method to find the IP.

This class also provides other static methods, but they are generally not used much. If you are interested, you can click on the open source code to take a look.

Then, we conduct a simple test through the main() method:

 public static void main(String[] args) throws IOException {
    //
    String href = "http://www.cncounter.com/tools/shorturl.php";
    // 端口号
    int port = parsePort(href);
    // 域名
    String host = parseHost(href);
    // IP 地址
    String address = parseIp(host);
  //
    System.out.println("host=" + host); 
    System.out.println("port=" + port); 
    System.out.println("address=" + address); 
  }
Copy after login

The execution result is:

host=www.cncounter.com
port=80
address=198.11.179.83
Copy after login

Knowing the IP and port number, we can connect directly through Socket.

Of course, if it is the http protocol, you can use Apache's HttpClient tool, which is powerful and easy to use. However, the disadvantage of this library is that the various versions are not compatible with each other, and the API is often changed. When programming, it needs to be processed according to a specific version number.

The complete code is as follows:

import java.io.IOException;
import java.net.*;
/**
 * 查找IP地址
 */
public class TestFindDNS {
  public static void main(String[] args) throws IOException {
    //
    String href = "http://www.cncounter.com/tools/shorturl.php";
    // 端口号
    int port = parsePort(href);
    // 域名
    String host = parseHost(href);
    // IP 地址
    String address = parseIp(host);
    //
    System.out.println("host=" + host);
    System.out.println("port=" + port);
    System.out.println("address=" + address);
  }
  /**
   * 获取端口号
   *
   * @param href 网址, ftp, http, nntp, ... 等等
   * @return
   * @throws IOException
   */
  public static int parsePort(String href) throws IOException {
    //
    URL url = new URL(href);
    // 端口号; 如果 href 中没有明确指定则为 -1
    int port = url.getPort();
    if (port < 0) {
      // 获取对应协议的默认端口号
      port = url.getDefaultPort();
    }
    return port;
  }
  /**
   * 获取Host部分
   *
   * @param href 网址, ftp, http, nntp, ... 等等
   * @return
   * @throws IOException
   */
  public static String parseHost(String href) throws IOException {
    //
    URL url = new URL(href);
    // 获取 host 部分
    String host = url.getHost();
    return host;
  }
  /**
   * 根据域名(host)解析IP地址
   *
   * @param host 域名
   * @return
   * @throws IOException
   */
  public static String parseIp(String host) throws IOException {
    // 根据域名查找IP地址
    InetAddress.getAllByName(host);
    InetAddress inetAddress = InetAddress.getByName(host);
    // IP 地址
    String address = inetAddress.getHostAddress();
    return address;
  }
}
Copy after login

OK, please encapsulate and process appropriately according to the specific situation.

The above content is how to query the DNS/IP address based on the URL in Java. I hope it can help everyone.

Related recommendations:

Detailed explanation of variable length parameter code in Java

Complete code example of Java encryption, decryption and digital signature

PHP programmers quickly develop Java

The above is the detailed content of Java method to query DNS/IP address based on website address. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles