001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.util;
018
019import java.io.File;
020import java.net.InetAddress;
021import java.net.MalformedURLException;
022import java.net.NetworkInterface;
023import java.net.SocketException;
024import java.net.URI;
025import java.net.URISyntaxException;
026import java.net.URL;
027import java.net.UnknownHostException;
028import java.util.Enumeration;
029
030import org.apache.logging.log4j.Logger;
031import org.apache.logging.log4j.status.StatusLogger;
032
033/**
034 * Networking-related convenience methods.
035 */
036public final class NetUtils {
037
038    private static final Logger LOGGER = StatusLogger.getLogger();
039    private static final String UNKNOWN_LOCALHOST = "UNKNOWN_LOCALHOST";
040
041    private NetUtils() {
042        // empty
043    }
044
045    /**
046     * This method gets the network name of the machine we are running on. Returns "UNKNOWN_LOCALHOST" in the unlikely
047     * case where the host name cannot be found.
048     *
049     * @return String the name of the local host
050     */
051    public static String getLocalHostname() {
052        try {
053            final InetAddress addr = InetAddress.getLocalHost();
054            return addr.getHostName();
055        } catch (final UnknownHostException uhe) {
056            try {
057                final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
058                while (interfaces.hasMoreElements()) {
059                    final NetworkInterface nic = interfaces.nextElement();
060                    final Enumeration<InetAddress> addresses = nic.getInetAddresses();
061                    while (addresses.hasMoreElements()) {
062                        final InetAddress address = addresses.nextElement();
063                        if (!address.isLoopbackAddress()) {
064                            final String hostname = address.getHostName();
065                            if (hostname != null) {
066                                return hostname;
067                            }
068                        }
069                    }
070                }
071            } catch (final SocketException se) {
072                LOGGER.error("Could not determine local host name", uhe);
073                return UNKNOWN_LOCALHOST;
074            }
075            LOGGER.error("Could not determine local host name", uhe);
076            return UNKNOWN_LOCALHOST;
077        }
078    }
079
080    /**
081     *  Returns the local network interface's MAC address if possible. The local network interface is defined here as
082     *  the {@link java.net.NetworkInterface} that is both up and not a loopback interface.
083     *
084     * @return the MAC address of the local network interface or {@code null} if no MAC address could be determined.
085     */
086    public static byte[] getMacAddress() {
087        byte[] mac = null;
088        try {
089            final InetAddress localHost = InetAddress.getLocalHost();
090            try {
091                final NetworkInterface localInterface = NetworkInterface.getByInetAddress(localHost);
092                if (isUpAndNotLoopback(localInterface)) {
093                    mac = localInterface.getHardwareAddress();
094                }
095                if (mac == null) {
096                    final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
097                    while (networkInterfaces.hasMoreElements() && mac == null) {
098                        final NetworkInterface nic = networkInterfaces.nextElement();
099                        if (isUpAndNotLoopback(nic)) {
100                            mac = nic.getHardwareAddress();
101                        }
102                    }
103                }
104            } catch (final SocketException e) {
105                LOGGER.catching(e);
106            }
107            if (mac == null || mac.length == 0) {
108                mac = localHost.getAddress();
109            }
110        } catch (final UnknownHostException ignored) {
111            // ignored
112        }
113        return mac;
114    }
115
116    /**
117     * Returns the mac address, if it is available, as a string with each byte separated by a ":" character.
118     * @return the mac address String or null.
119     */
120    public static String getMacAddressString() {
121        final byte[] macAddr = getMacAddress();
122        if (macAddr != null && macAddr.length > 0) {
123            StringBuilder sb = new StringBuilder(String.format("%02x", macAddr[0]));
124            for (int i = 1; i < macAddr.length; ++i) {
125                sb.append(":").append(String.format("%02x", macAddr[i]));
126            }
127            return sb.toString();
128
129        }
130        return null;
131    }
132
133    private static boolean isUpAndNotLoopback(final NetworkInterface ni) throws SocketException {
134        return ni != null && !ni.isLoopback() && ni.isUp();
135    }
136
137    /**
138     * Converts a URI string or file path to a URI object.
139     *
140     * @param path the URI string or path
141     * @return the URI object
142     */
143    public static URI toURI(final String path) {
144        try {
145            // Resolves absolute URI
146            return new URI(path);
147        } catch (final URISyntaxException e) {
148            // A file path or a Apache Commons VFS URL might contain blanks.
149            // A file path may start with a driver letter
150            try {
151                final URL url = new URL(path);
152                return new URI(url.getProtocol(), url.getHost(), url.getPath(), null);
153            } catch (MalformedURLException | URISyntaxException nestedEx) {
154                return new File(path).toURI();
155            }
156        }
157    }
158
159}