Java get current domain name


Answers ( 1 )


    In Java, obtaining the current domain name depends on the context in which your code is running. If you're working within a web application (like a Servlet), you can get the domain name from the request object. Here's how you can do it:

    1. Servlet Environment: If you're running a Servlet, you can use the HttpServletRequest object to get the current URL and then extract the domain from it. Here's an example:

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String url = request.getRequestURL().toString();
          String domain = new URL(url).getHost();
          // Now 'domain' contains the domain name

      In this code, getRequestURL() returns the full URL, and new URL(url).getHost() extracts the domain name from it.

    2. Non-Web Context: If you are not in a web application context, getting the "current domain name" is less clear. Usually, in standalone Java applications, there's no concept of a "domain" as in web applications. However, if you need the domain name of the machine where the code is running, you can get the hostname (which might not be a fully qualified domain name):

      public class Main {
          public static void main(String[] args) {
              try {
                  String hostName = InetAddress.getLocalHost().getHostName();
                  // hostName will have the hostname of the current machine
              } catch (Exception e) {

      Keep in mind that InetAddress.getLocalHost().getHostName() might not return a fully qualified domain name. It returns the hostname as known to the underlying system.

    Remember, the concept of a "current domain name" is usually relevant in web applications. In other contexts, you might need to clarify what you mean by "domain name."

Leave an answer