In Java, you can use the command Runtime.getRuntime().exec to execute shell commands, or any external system command.

  p = Runtime.getRuntime().exec("host -t a " + domain);
  p.waitFor();
 
  BufferedReader reader = 
     new BufferedReader(new InputStreamReader(
	 p.getInputStream()));
  String line = reader.readLine();
  while (line != null) {
	line = reader.readLine();
  }

1. IP Address example

See below example, execute shell command host -t a google.com to get all IP addresses that attached to google.com, later uses IP regular expression pattern to display only the IP address.

ExecuteShellComand.java
package com.mkyong;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ExecuteShellComand {
 
	private static final String IPADDRESS_PATTERN = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])"
			+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])"
			+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])"
			+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
 
	private static Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
	private static Matcher matcher;
 
	public static void main(String[] args) {
 
		String domain = "google.com";
 
		Process p;
		try {
			p = Runtime.getRuntime().exec("host -t a " + domain);
			p.waitFor();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
 
			StringBuffer sb = new StringBuffer();
 
			String line = reader.readLine();
			sb.append(line);
			while (line != null) {
				line = reader.readLine();
				sb.append(line);
			}
 
			List<String> list = getIpAddress(sb.toString());
 
			if (list.size() > 0) {
				System.out.println(domain + " has address : ");
				for (String ip : list) {
					System.out.println(ip);
				}
			} else {
				System.out.println(domain + " has NO address.");
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		}
 
	}
 
	public static List<String> getIpAddress(String msg) {
 
		List<String> ipList = new ArrayList<String>();
 
		if (msg == null || msg.equals(""))
			return ipList;
 
		matcher = pattern.matcher(msg);
		while (matcher.find()) {
			ipList.add(matcher.group(0));
		}
 
		return ipList;
	}
}

Output

google.com has address : 
74.125.135.139
74.125.135.100
74.125.135.101
74.125.135.102
74.125.135.113
74.125.135.138

References

  1. Runtime.getRuntime().exec JavaDoc
  2. How To Validate IP Address With Regular Expression
Tags :
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus.
Here are some of my recommended Books

Related Posts

Popular Posts