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

2

6

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).

Blindheim answered 26/12, 2012 at 15:41 Comment(2)
Does the solution need to be platform independent, and if not, which platform will it run on?Yore
You can look at this question : #10262495Repulsive
W
15

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();
}
Widespread answered 26/12, 2012 at 15:46 Comment(0)
W
1

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.
Wisent answered 26/10, 2021 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.