开发者

How can you check whether domain exists or not in Java?

开发者 https://www.devze.com 2023-03-03 16:34 出处:网络
Suppose my email address is xyz@yahoo.com and I want to check if yahoo.com is a valid domain or not. Can any开发者_如何转开发one tell me which Java API I can use for this?InetAddress has getByName()

Suppose my email address is xyz@yahoo.com and I want to check if yahoo.com is a valid domain or not.

Can any开发者_如何转开发one tell me which Java API I can use for this?


InetAddress has getByName() method to determine the IP address of a host, given the host's name.

If no IP address for the host could be found ( in case the given host name is not valid) , UnknownHostException will be thrown.

So , you just try to catch an UnknownHostException when calling InetAddress.getByName() . If UnknownHostException is caught , that means your input host name is invalid.


One thing that you could do is trying to resolve "yahoo.com". Something like this:

public static void main(String[] args) throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getByName("yahoo.com");
    System.out.println(inetAddress.getHostName());
    System.out.println(inetAddress.getHostAddress());
}

which outputs:

yahoo.com
67.195.160.76


Another possibility is to check the MX of the entered domain.

http://www.mxtoolbox.com/SuperTool.aspx

It is not Java API, but you can always parse the HTML response.

It means if the provider of the mail service is not blacklisted it could be safe and a real address.

But as already said, some server could always define security restriction to such service.

Another point, some services exist to provide temporary emails (mailinator.com, jetable.org, and so on...) You have to check these domains as well if you want to prevent a user to register with such an email.

UPDATE

Google provides a DNS check site which seems to be free.

An example: https://dns.google/resolve?name=amazon.com&type=MX returns a page with the following JSON:

{
  "Status": 0,
  "TC": false,
  "RD": true,
  "RA": true,
  "AD": false,
  "CD": false,
  "Question": [
    {
      "name": "amazon.com.",
      "type": 15
    }
  ],
  "Answer": [
    {
      "name": "amazon.com.",
      "type": 15,
      "TTL": 724,
      "data": "5 amazon-smtp.amazon.com."
    }
  ]
}


You can use org.apache.commons.validator.routines.DomainValidator.

First add maven dependency

<dependency>
        <groupId>commons-validator</groupId>
        <artifactId>commons-validator</artifactId>
        <version>1.6</version>
</dependency>

then:

boolean isValid = DomainValidator.getInstance().isValid("yahoo.com");


I don't know if it's the best way to this, but I've done something similar for a VB.NET program:

I just pinged the domain, and if I didn't get a reply, the domain either was offline or didn't exist.

0

精彩评论

暂无评论...
验证码 换一张
取 消