Java server host name

I think the only real uname (uts_name) backed name is from the RMI/JMX VMID, but this is implementation specific.

Maybe of interest: On GNU/Linux (and certainly others), it turns out that the command hostname(1) results in the system call uname(3) (defined in POSIX), found in /usr/include/sys/utsname.h . (Try it by running strace hostname ). The corresponding command is uname(1) . Thus to obtain the so-called «hostname», really the «nodename» one can use the command uname —nodename too. This should (generally) be the string that can be found in /etc/hostname .

12 Answers 12

Strictly speaking — you have no choice but calling either hostname(1) or — on Unix gethostname(2) . This is the name of your computer. Any attempt to determine the hostname by an IP address like this

InetAddress.getLocalHost().getHostName() 

is bound to fail in some circumstances:

  • The IP address might not resolve into any name. Bad DNS setup, bad system setup or bad provider setup may be the reason for this.
  • A name in DNS can have many aliases called CNAMEs. These can only be resolved in one direction properly: name to address. The reverse direction is ambiguous. Which one is the «official» name?
  • A host can have many different IP addresses — and each address can have many different names. Two common cases are: One ethernet port has several «logical» IP addresses or the computer has several ethernet ports. It is configurable whether they share an IP or have different IPs. This is called «multihomed».
  • One Name in DNS can resolve to several IP Addresses. And not all of those addresses must be located on the same computer! (Usecase: A simple form of load-balancing)
  • Let’s not even start talking about dynamic IP addresses.

Also don’t confuse the name of an IP-address with the name of the host (hostname). A metaphor might make it clearer:

There is a large city (server) called «London». Inside the city walls much business happens. The city has several gates (IP addresses). Each gate has a name («North Gate», «River Gate», «Southampton Gate». ) but the name of the gate is not the name of the city. Also you cannot deduce the name of the city by using the name of a gate — «North Gate» would catch half of the bigger cities and not just one city. However — a stranger (IP packet) walks along the river and asks a local: «I have a strange address: ‘Rivergate, second left, third house’. Can you help me?» The local says: «Of course, you are on the right road, simply go ahead and you will arrive at your destination within half an hour.»

This illustrates it pretty much I think.

Читайте также:  Java date and time pattern

The good news is: The real hostname is usually not necessary. In most cases any name which resolves into an IP address on this host will do. (The stranger might enter the city by Northgate, but helpful locals translate the «2nd left» part.)

In the remaining corner cases you must use the definitive source of this configuration setting — which is the C function gethostname(2) . That function is also called by the program hostname .

Источник

How to get host name with port from a http or https request

I have two applications deployed in a JBoss container (same unix box). If I receive a request from app1, I need to send a corresponding request for app2. An Example: If app1 requests: http://example.com/context?param1=123 , then I need to extract http://example.com/ , so that I can send the request for the second app. I tried using

 HttpServletRequest.getServerName() & HttpServletRequest.getServerPort() & \ HttpServletRequest.getHeader("host") 

7 Answers 7

You can use HttpServletRequest.getScheme() to retrieve either «http» or «https».

Using it along with HttpServletRequest.getServerName() should be enough to rebuild the portion of the URL you need.

You don’t need to explicitly put the port in the URL if you’re using the standard ones (80 for http and 443 for https).

Edit: If your servlet container is behind a reverse proxy or load balancer that terminates the SSL, it’s a bit trickier because the requests are forwarded to the servlet container as plain http. You have a few options:

  1. Use HttpServletRequest.getHeader(«x-forwarded-proto») instead; this only works if your load balancer sets the header correctly (Apache should afaik).
  2. Configure a RemoteIpValve in JBoss/Tomcat that will make getScheme() work as expected. Again, this will only work if the load balancer sets the correct headers.
  3. If the above don’t work, you could configure two different connectors in Tomcat/JBoss, one for http and one for https, as described in this article.

Источник

How to configure hostname resolution to use a custom DNS server in Java?

java.net.InetAddress resolves hostnames using the local machine’s default host-name resolver by default:

Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS). The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned. [source]

How can we configure this behavior without modifying the local machine’s default hostname resolver? For example, is there anyway to configure java.net.InetAddress such that it resolves host names through OpenDNS (208.67.222.222, 208.67.220.220) or Google Public DNS (2001:4860:4860::8888, 2001:4860:4860::8844)? Or is the only solution to explicitly create DNS packet requests, send them to the servers through either java.net.DatagramSocket or java.net.Socket, and parse the responses?

Читайте также:  Number format with comma in php

5 Answers 5

Java 9 removed this capability. You will need to use a third party DNS client library.

If you are using Java 8 or older you can do:

You can set the system property sun.net.spi.nameservice.nameservers as documented by this site.

As documented in the same site: «These properties may not be supported in future releases.» Is there another way to achieve that?

No. Not if you want to use java.net.InetAddress . If you’re ok using a different mechanism then you could of course use a 3rd party DNS library ( e.g. dnsjava ). The only real reason the properties might change is if Oracle overhauls the java.net implementation in some future version of Java. If this happens they will likely provide an a new solution to this problem at that time as well.

with the following Interface and allowing access to java.net.* it is possible to use own DNS provider with JDK8 and JDK9. The new Provider is installed via «INameService.install(new MyNameService());»

public interface INameService extends InvocationHandler < public static void install(final INameService dns) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException < final ClassinetAddressClass = InetAddress.class; Object neu; Field nameServiceField; try < final Classiface = Class.forName("java.net.InetAddress$NameService"); nameServiceField = inetAddressClass.getDeclaredField("nameService"); neu = Proxy.newProxyInstance(iface.getClassLoader(), new Class[] < iface >, dns); > catch(final ClassNotFoundException|NoSuchFieldException e) < nameServiceField = inetAddressClass.getDeclaredField("nameServices"); final Classiface = Class.forName("sun.net.spi.nameservice.NameService"); neu = Arrays.asList(Proxy.newProxyInstance(iface.getClassLoader(), new Class[] < iface >, dns)); > nameServiceField.setAccessible(true); nameServiceField.set(inetAddressClass, neu); > /** * Lookup a host mapping by name. Retrieve the IP addresses associated with a host * * @param host the specified hostname * @return array of IP addresses for the requested host * @throws UnknownHostException if no IP address for the could be found */ InetAddress[] lookupAllHostAddr(final String host) throws UnknownHostException; /** * Lookup the host corresponding to the IP address provided * * @param addr byte array representing an IP address * @return representing the host name mapping * @throws UnknownHostException * if no host found for the specified IP address */ String getHostByAddr(final byte[] addr) throws UnknownHostException; @Override default public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable < switch(method.getName()) < case "lookupAllHostAddr": return lookupAllHostAddr((String)args[0]); case "getHostByAddr" : return getHostByAddr ((byte[])args[0]); default : final StringBuilder o = new StringBuilder(); o.append(method.getReturnType().getCanonicalName()+" "+method.getName()+"("); final Class[] ps = method.getParameterTypes(); for(int i=0;i0) o.append(", "); o.append(ps[i].getCanonicalName()).append(" p").append(i); > o.append(")"); throw new UnsupportedOperationException(o.toString()); > > > 

Источник

Читайте также:  Html coding linking pages

How can I get a the host name (with port) that a servlet is at

I thought ServletContext might provide a method. Does the getAttribute() method of ServletContext provide any help i.e. is there an attribute name (maybe «host», «port») that will be of help. The reason for this is I want my application to run wherever it is deployed, and at one point I have to allow a user to click a link that points to a location on the file server. Hence I need to reference by the host and port and cannot use an internal reference.

5 Answers 5

ServletRequest.getServerName(. ) ServletRequest.getServerPort(. ) 

These methods simply use the value of the Host header from the request, which isn’t always safe to use, since it can be altered by anyone, including any proxies between the client and server. So for example, if your Tomcat instance is behind an Apache server, these methods will likely return a localhost address (see the comments on this answer)

The ServletRequest object that has been passed to your doGet, or doPost method has getServerName and getServerPort methods that provide this information.

public void doGet(ServletRequest request, ServletResponse response) < System.out.println("Host = " + request.getServerName()); System.out.println("Port mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f2.5%2f" data-se-share-sheet-license-name="CC BY-SA 2.5" data-s-popover-placement="bottom-start">Share
answered Apr 7, 2010 at 9:16
1
    1
    To get an url: request.getServerName() + ":" + request.getServerPort();
    – Simon Bengtsson
    Oct 26, 2014 at 9:12
Add a comment|
8

@Everyone has a good answer. But taking scheme, server name and port then mergin them. There is a simpler way:

You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL(); String uri = request.getRequestURI(); String host = url.substring(0, url.indexOf(uri)); //result

Источник

Оцените статью