Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I look up a DNS MX record for a given server in Java?

Anybody knows how to get MX address (from for example gmail.com) in java using standard libraries? Or do I need to download external one?

I'm using netbeans if it can be helpful (if it provides something for this).

like image 695
oneat Avatar asked Dec 26 '12 15:12

oneat


2 Answers

I was also searching for standart lib for this in java. Unsuccessful.

Then I have used dnsjava.

private Record[] lookupMxRecords(final String domainPart) throw TextParseException
{
    final Lookup dnsLookup = new Lookup(domainPart, Type.MX);
    return dnsLookup.run();
}
like image 134
Walery Strauch Avatar answered Oct 15 '22 02:10

Walery Strauch


Main.java

import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class Main {
    public static void main(String args[]) throws Exception {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        env.put("java.naming.provider.url", "dns://8.8.8.8/");
        DirContext ctx = new InitialDirContext(env);
        Attributes attrsl = ctx.getAttributes("google.com", new String[] {"MX"});
        Attribute attr = attrsl.get("MX");
        if (attr != null) {
            System.out.println("MX records:");
            for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                System.out.println(vals.nextElement());
            }
        }
    }
}

issues

$ javac Main.java && java Main
MX records:
20 alt1.aspmx.l.google.com.
50 alt4.aspmx.l.google.com.
10 aspmx.l.google.com.
40 alt3.aspmx.l.google.com.
30 alt2.aspmx.l.google.com.
like image 20
Gerrit Griebel Avatar answered Oct 15 '22 02:10

Gerrit Griebel