2

How can I get the location of the hosts file when using my application on different platforms?

3 Answers 3

3

think that you would have to roll your own here I'm afraid, as this is a pretty low level system function, I think that it's a little beyond what you could expect java to do for you.

This link points to some special options that you can set to alter the bind order, I don't think that they will tell you where the hosts file is, but you could could investigate in and around these options to see if you can find anything else to help you

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, too bad there isn't an easier way.
1

You could use the "os.name" system property to determine the operating system. Then, retrieve the hosts file depending on where each operating system stores it. For example:

String osName = System.getProperty("os.name").toLowerCase();
File hostsFile;
if (osName.startsWith("mac os x")){
  hostFile = new File("/etc/hosts");
} else if (osName.contains("windows")){
  hostFile = //...
}

Comments

1

Take a look at the hosts file locations for each operating system and version on Wikipedia. Unfortunately you will have to implement your own logic similar to Michael's answer:

import java.awt.Desktop;
import java.io.File;

public class HostsFile
{
    public static void main(String[] args) throws Exception
    {
        String osName = System.getProperty("os.name");

        File hostsFile = null;

        if (osName.contains("Windows"))
        {
            hostsFile = new File(System.getenv("WinDir")
                    + "\\system32\\drivers\\etc\\hosts");
        }

        Desktop.getDesktop().open(hostsFile);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.