Skip to content

Instantly share code, notes, and snippets.

@stropdale
Created July 29, 2019 15:50
Show Gist options
  • Save stropdale/02470e2417c1beb63c7c840c8fa16c3d to your computer and use it in GitHub Desktop.
Save stropdale/02470e2417c1beb63c7c840c8fa16c3d to your computer and use it in GitHub Desktop.
DNS IP Address Lookup from Host name in Java
// Needs to be run on async otherwise you will get a crash.
// Make sure you have the internet permission added to the app manifest if this is going in an Anrdoid app...
<uses-permission android:name="android.permission.INTERNET" />
public class DnsLookup extends AsyncTask<ArrayList<String>, Integer, ArrayList<HostIpDetails>> {
private static String TAG = "DnsLookup";
public interface DnsLookUpCompletionListener {
void completed(ArrayList<HostIpDetails> hostDetails);
}
private String mFoundIp;
private DnsLookUpCompletionListener mListener;
public void excuteWithListener(ArrayList<String> strings, DnsLookUpCompletionListener listener) {
mListener = listener;
execute(strings);
}
@Override
protected ArrayList<HostIpDetails> doInBackground(ArrayList<String>... strings) {
ArrayList<HostIpDetails> details = new ArrayList<>();
if (strings.length == 0) {
return details;
}
ArrayList<String> hostNames = strings[0];
for (String hostName : hostNames) {
try {
InetAddress inet = InetAddress.getByName(hostName.toLowerCase());
String hostIp = inet.getHostAddress();
if (hostIp != null) {
details.add(new HostIpDetails(hostName, hostIp));
}
} catch (UnknownHostException e) {
e.printStackTrace();
Log.i(TAG, "Host " + hostName + " not found");
}
}
return details;
}
@Override
protected void onPostExecute(ArrayList<HostIpDetails> hostIpDetails) {
if (mListener != null) {
mListener.completed(hostIpDetails);
}
}
}
//==================================
// Host Info Model Class
public class HostIpDetails {
private String mHostName;
private String mHostIp;
public HostIpDetails(String hostName, String hostIp) {
mHostName = hostName;
mHostIp = hostIp;
}
public String getHostName() {
return mHostName;
}
public String getHostIp() {
return mHostIp;
}
}
//==================================
// TO RUN IT...
ArrayList<String> ips = new ArrayList<>();
ips.add(hostName);
DnsLookup lookup = new DnsLookup();
lookup.excuteWithListener(ips, new DnsLookup.DnsLookUpCompletionListener() {
@Override
public void completed(ArrayList<HostIpDetails> hostDetails) {
// Returns an Array of found host details.
}
});
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment