Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

In this page you can find the example usage for java.net InetAddress getHostName.

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:nl.nn.adapterframework.util.Misc.java

public static String getHostname() {
    String localHost = null;//from w  w w.j av  a  2s  . co m
    // String localIP="";
    try {
        InetAddress localMachine = InetAddress.getLocalHost();
        //localIP = localMachine.getHostAddress();
        localHost = localMachine.getHostName();
    } catch (UnknownHostException uhe) {
        if (localHost == null) {
            localHost = "unknown (" + uhe.getMessage() + ")";
        }
    }
    return localHost;
}

From source file:adams.core.net.InternetHelper.java

/**
 * Returns the host name determined from the network interfaces.
 *
 * @return       the host name, null if none found
 *//*from  w ww  .  j  av a  2 s .  c  o m*/
public static synchronized String getHostnameFromNetworkInterface() {
    String result;
    List<String> list;
    Enumeration<NetworkInterface> enmI;
    NetworkInterface intf;
    Enumeration<InetAddress> enmA;
    InetAddress addr;
    boolean found;

    result = null;

    if (m_HostnameNetworkInterface == null) {
        list = new ArrayList<>();
        found = false;
        try {
            enmI = NetworkInterface.getNetworkInterfaces();
            while (enmI.hasMoreElements()) {
                intf = enmI.nextElement();
                // skip non-active ones
                if (!intf.isUp())
                    continue;
                enmA = intf.getInetAddresses();
                while (enmA.hasMoreElements()) {
                    addr = enmA.nextElement();
                    list.add(addr.getHostName());
                    if (addr.getHostName().indexOf(':') == -1) {
                        result = addr.getHostName();
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
        } catch (Exception e) {
            // ignored
        }

        if (result == null) {
            if (list.size() > 0)
                result = list.get(0);
            else
                result = "<unknown>";
        }

        m_HostnameNetworkInterface = result;
    } else {
        result = m_HostnameNetworkInterface;
    }

    return result;
}

From source file:eu.eubrazilcc.lvl.core.util.NetworkingUtils.java

/**
 * Gets the first public IP address of the host. If no public address are found, one of the private
 * IPs are randomly selected. Otherwise, it returns {@code localhost}.
 * @return the first public IP address of the host.
 *//*  ww w.  j av  a 2s. c  om*/
public static final String getInet4Address() {
    String inet4Address = null;
    final List<String> localAddresses = new ArrayList<String>();
    try {
        final Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        if (networks != null) {
            final List<NetworkInterface> ifs = Collections.list(networks);
            for (int i = 0; i < ifs.size() && inet4Address == null; i++) {
                final Enumeration<InetAddress> inetAddresses = ifs.get(i).getInetAddresses();
                if (inetAddresses != null) {
                    final List<InetAddress> addresses = Collections.list(inetAddresses);
                    for (int j = 0; j < addresses.size() && inet4Address == null; j++) {
                        final InetAddress address = addresses.get(j);
                        if (address instanceof Inet4Address && !address.isAnyLocalAddress()
                                && !address.isLinkLocalAddress() && !address.isLoopbackAddress()
                                && StringUtils.isNotBlank(address.getHostAddress())) {
                            final String hostAddress = address.getHostAddress().trim();
                            if (!hostAddress.startsWith("10.") && !hostAddress.startsWith("172.16.")
                                    && !hostAddress.startsWith("192.168.")) {
                                inet4Address = hostAddress;
                            } else {
                                localAddresses.add(hostAddress);
                            }
                            LOGGER.trace(
                                    "IP found - Name: " + address.getHostName() + ", Addr: " + hostAddress);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Failed to discover public IP address for this host", e);
    }
    return (StringUtils.isNotBlank(inet4Address) ? inet4Address
            : (!localAddresses.isEmpty() ? localAddresses.get(new Random().nextInt(localAddresses.size()))
                    : "localhost")).trim();
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static String getSocketConnectString(InetSocketAddress socketAddress) {
    String host;// w ww . ja va 2 s .  co m
    InetAddress address = socketAddress.getAddress();
    if (address == null) {
        host = socketAddress.getHostString();
    } else if (address.isAnyLocalAddress() || address.isLoopbackAddress()) {
        host = address.getCanonicalHostName();
    } else {
        host = address.getHostName();
    }
    return host + ":" + socketAddress.getPort();
}

From source file:adams.core.net.InternetHelper.java

/**
 * Returns the IP address determined from the network interfaces (using
 * the IP address of the one with a proper host name).
 *
 * @return       the IP address//from   w w  w .j ava  2  s.  c  o m
 */
public static synchronized String getIPFromNetworkInterface() {
    String result;
    List<String> list;
    Enumeration<NetworkInterface> enmI;
    NetworkInterface intf;
    Enumeration<InetAddress> enmA;
    InetAddress addr;
    boolean found;

    result = null;

    if (m_IPNetworkInterface == null) {
        list = new ArrayList<>();
        found = false;
        try {
            enmI = NetworkInterface.getNetworkInterfaces();
            while (enmI.hasMoreElements()) {
                intf = enmI.nextElement();
                // skip non-active ones
                if (!intf.isUp())
                    continue;
                enmA = intf.getInetAddresses();
                while (enmA.hasMoreElements()) {
                    addr = enmA.nextElement();
                    list.add(addr.getHostAddress());
                    if (addr.getHostName().indexOf(':') == -1) {
                        result = addr.getHostAddress();
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
        } catch (Exception e) {
            // ignored
        }

        if (result == null) {
            if (list.size() > 0)
                result = list.get(0);
            else
                result = "<unknown>";
        }

        m_IPNetworkInterface = result;
    } else {
        result = m_IPNetworkInterface;
    }

    return result;
}

From source file:test.be.fedict.eid.applet.MiscTest.java

@Test
public void hostname() throws Exception {
    InetAddress address = InetAddress.getLocalHost();
    String hostname = address.getHostName();
    LOG.debug("hostname: " + hostname);
}

From source file:org.apache.hms.common.util.MulticastDNS.java

public MulticastDNS() throws UnknownHostException {
    super();/* ww w. j ava  2  s  .co  m*/
    InetAddress addr = InetAddress.getLocalHost();
    String hostname = addr.getHostName();
    if (hostname.indexOf('.') > 0) {
        hostname = hostname.substring(0, hostname.indexOf('.'));
    }
    svcName = hostname;
    settings = new Hashtable<String, String>();
    settings.put("host", svcName);
    settings.put("port", new Integer(svcPort).toString());
}

From source file:info.raack.appliancedetection.common.service.EmailErrorService.java

@PostConstruct
void init() {/* w  ww . j  ava2s .  c  o m*/
    try {
        InetAddress addr = InetAddress.getLocalHost();
        // Get hostname
        hostname = addr.getHostName();
    } catch (UnknownHostException e) {
        hostname = "unknown";
    }
}

From source file:de.avanux.livetracker.mobile.ConfigurationProvider.java

private Properties buildConfiguration() {
    Properties configuration = new Properties();
    configuration.put(ConfigurationConstants.ID, "" + TrackingManager.createTracking().getTrackingID());
    configuration.put(ConfigurationConstants.SERVER_API_VERSION, "1");
    configuration.put(ConfigurationConstants.MIN_TIME_INTERVAL,
            "" + Configuration.getInstance().getMinTimeInterval());
    configuration.put(ConfigurationConstants.MESSAGE_TO_USERS, Configuration.getInstance().getMessageToUsers());

    // FIXME: this is a hack during main development phase to switch easily between development server and deployment server
    String hostname = null;//  w  w  w. j  a  v a  2 s  .  co m
    try {
        InetAddress addr = InetAddress.getLocalHost();
        hostname = addr.getHostName();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    if ((hostname != null) && hostname.equals("miraculix")) {
        configuration.put(ConfigurationConstants.LOCATION_RECEIVER_URL,
                "http://miraculix.localnet:8080/LiveTrackerServer/LocationReceiver");
    } else {
        configuration.put(ConfigurationConstants.LOCATION_RECEIVER_URL,
                "http://livetracker.dyndns.org/LocationReceiver");
    }
    return configuration;
}

From source file:org.anyframe.iam.audit.web.filter.AuditLoggingFilter.java

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    String methodName = StringUtil.trim(request.getRequestURI(), request.getContextPath());
    String itemId = StringUtil.trim(request.getRequestURI(), request.getContextPath());
    String itemName = request.getRequestURI();

    try {//from ww  w . ja va 2  s.  co m
        // SpringSecurity Resources
        Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication();
        Object obj = (authentication != null) ? (Object) authentication.getPrincipal() : null;
        WebAuthenticationDetails details = (authentication != null)
                ? (WebAuthenticationDetails) authentication.getDetails()
                : null;

        String username = (obj != null)
                ? ((obj instanceof UserDetails) ? ((UserDetails) obj).getUsername() : obj.toString())
                : "anonymous";
        String clientIp = request.getRemoteAddr();
        InetAddress addr = InetAddress.getLocalHost();
        String hostName = addr.getHostName();

        // Audit Log Message
        AuditLogService auditLogService = (AuditLogService) context.getBean("auditLogService");
        AuditLog auditLog = new AuditLog();
        auditLog.setLogMessage(methodName);
        auditLog.setLogonName(username);
        auditLog.setActionType("Web");
        auditLog.setItemType("Url");
        auditLog.setActionStatus("Success");
        auditLog.setItemId(itemId);
        auditLog.setItemName(itemName);
        auditLog.setHostName(hostName);
        auditLog.setClientIP(clientIp);

        // Audit Log Write
        auditLogService.insertAuditLog(auditLog);
    } catch (Exception e) {
        LOGGER.error("Error occured during audit logging.\n Cause : " + e.getMessage());
    }
    filterChain.doFilter(request, response);
}