The DNS Lookup Tool in Java (InetAddress)

  • 时间:2020-10-05 13:36:40
  • 分类:网络文摘
  • 阅读:107 次

Have you ever needed a quick tool to lookup multiple hosts (IP address by getHostAddress)? It turns out it is very simple to write a tool in Java based on the InetAddress class.

The following Java code has been uploaded to github: https://github.com/DoctorLai/DNSLookup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class DNSLookup {
  // https://helloacm.com/the-dns-lookup-tool-in-java-inetaddress/
  public static void main(String args[]) {
    try {
      InetAddress host;
      if (args.length == 0) {
        host = InetAddress.getLocalHost();
        displayHost(host);
      } else {
        for (int i = 0; i < args.length; ++ i) {
          host = InetAddress.getByName(args[i]);
          displayHost(host);
        }
      }      
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }
 
  private static void displayHost(InetAddress host) {
    System.out.println("Host:'" + host.getHostName()
          + "' has address: " + host.getHostAddress());    
  }
}  
import java.net.InetAddress;
import java.net.UnknownHostException;

public class DNSLookup {
  // https://helloacm.com/the-dns-lookup-tool-in-java-inetaddress/
  public static void main(String args[]) {
    try {
      InetAddress host;
      if (args.length == 0) {
        host = InetAddress.getLocalHost();
        displayHost(host);
      } else {
        for (int i = 0; i < args.length; ++ i) {
          host = InetAddress.getByName(args[i]);
          displayHost(host);
        }
      }      
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }

  private static void displayHost(InetAddress host) {
    System.out.println("Host:'" + host.getHostName()
          + "' has address: " + host.getHostAddress());    
  }
}  

The above when compiled using javac DNSLookup.java generates DNSLookup.class (or download a pre-compiled version). And you can query the Host IP addresses based on the InetAddress.getHostAddress method.

# java DNSLookup
Host:'HP-PC' has address: 192.168.0.102

[email protected] D:\
# java DNSLookup localhost
Host:'localhost' has address: 127.0.0.1

[email protected] D:\
# java DNSLookup localhost www.google.com
Host:'localhost' has address: 127.0.0.1
Host:'www.google.com' has address: 216.58.201.36

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
为何网站内容稳定更新还没有关键词排名?  图中阴影部分面积是多少平方厘米  梯形ABCD的面积是多少平方厘米  某校一年级同学平均身高是115厘米  若这稿件由乙完成,需要几小时?  从上边剪下一块直径是80厘米的圆片  甲乙丙三个修路队共同修完一条公路  最多可做多少面小三角旗  客车从甲地开往乙地需要10小时  遇店加一半,遇花喝一斗 
评论列表
添加评论