/*
 * MIT License
 *
 * Copyright (c) 2019-2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package oshi.software.common;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import oshi.annotation.concurrent.ThreadSafe;
import oshi.software.os.NetworkParams;
import oshi.util.FileUtil;
import oshi.util.ParseUtil;

/**
 * Common NetworkParams implementation.
 */
@ThreadSafe
public abstract class AbstractNetworkParams implements NetworkParams {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractNetworkParams.class);
    private static final String NAMESERVER = "nameserver";

    @Override
    public String getDomainName() {
        try {
            return InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException e) {
            LOG.error("Unknown host exception when getting address of local host: {}", e.getMessage());
            return "";
        }
    }

    @Override
    public String getHostName() {
        try {
            String hn = InetAddress.getLocalHost().getHostName();
            int dot = hn.indexOf('.');
            if (dot == -1) {
                return hn;
            }
            return hn.substring(0, dot);
        } catch (UnknownHostException e) {
            LOG.error("Unknown host exception when getting address of local host: {}", e.getMessage());
            return "";
        }
    }

    @Override
    public String[] getDnsServers() {
        List<String> resolv = FileUtil.readFile("/etc/resolv.conf");
        String key = NAMESERVER;
        int maxNameServer = 3;
        List<String> servers = new ArrayList<>();
        for (int i = 0; i < resolv.size() && servers.size() < maxNameServer; i++) {
            String line = resolv.get(i);
            if (line.startsWith(key)) {
                String value = line.substring(key.length()).replaceFirst("^[ \t]+", "");
                if (value.length() != 0 && value.charAt(0) != '#' && value.charAt(0) != ';') {
                    String val = value.split("[ \t#;]", 2)[0];
                    servers.add(val);
                }
            }
        }
        return servers.toArray(new String[0]);
    }

    /**
     * Convenience method to parse the output of the `route` command. While the
     * command arguments vary between OS's the output is consistently parsable.
     *
     * @param lines
     *            output of OS-specific route command
     * @return default gateway
     */
    protected static String searchGateway(List<String> lines) {
        for (String line : lines) {
            String leftTrimmed = line.replaceFirst("^\\s+", "");
            if (leftTrimmed.startsWith("gateway:")) {
                String[] split = ParseUtil.whitespaces.split(leftTrimmed);
                if (split.length < 2) {
                    return "";
                }
                return split[1].split("%")[0];
            }
        }
        return "";
    }

    @Override
    public String toString() {
        return String.format("Host name: %s, Domain name: %s, DNS servers: %s, IPv4 Gateway: %s, IPv6 Gateway: %s",
                this.getHostName(), this.getDomainName(), Arrays.toString(this.getDnsServers()),
                this.getIpv4DefaultGateway(), this.getIpv6DefaultGateway());

    }
}

@@ -39,17 +39,17 @@
 2019-202
-1
+2
  The OSH
@@ -1379,66 +1379,8 @@
 t;%0A%0A
-import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0A
 impo
@@ -1652,100 +1652,8 @@
  %7B%0A%0A
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractNetworkParams.class);%0A
     
@@ -1750,32 +1750,63 @@
 tDomainName() %7B%0A
+        InetAddress localHost;%0A
         try %7B%0A  
@@ -1815,22 +1815,27 @@
         
-return
+localHost =
  InetAdd
@@ -1857,31 +1857,8 @@
 st()
-.getCanonicalHostName()
 ;%0A  
@@ -1914,104 +1914,64 @@
     
-LOG.error(%22Unknown host exception when getting address of local host: %7B%7D%22, e.getMessage()
+localHost = InetAddress.getLoopbackAddress(
 );%0A    
+    %7D%0A
     
@@ -1977,37 +1977,57 @@
      return 
-%22%22;%0A        %7D
+localHost.getCanonicalHostName();
 %0A    %7D%0A%0A    
@@ -2082,62 +2082,237 @@
     
-try %7B%0A            String hn = InetAddress.getL
+InetAddress localHost;%0A        try %7B%0A            localHost = InetAddress.getLocalHost();%0A        %7D catch (UnknownHostException e) %7B%0A            localHost = InetAddress.getLoopbackAddress();%0A        %7D%0A        String hn = l
 ocalHost
 ().g
@@ -2307,18 +2307,16 @@
 ocalHost
-()
 .getHost
@@ -2319,28 +2319,24 @@
 HostName();%0A
-    
         int 
@@ -2358,20 +2358,16 @@
 f('.');%0A
-    
         
@@ -2387,36 +2387,32 @@
 ) %7B%0A            
-    
 return hn;%0A     
@@ -2406,36 +2406,32 @@
 urn hn;%0A        
-    
 %7D%0A            re
@@ -2416,36 +2416,32 @@
       %7D%0A        
- 
-   
 return hn.substr
@@ -2457,188 +2457,8 @@
 t);%0A
-        %7D catch (UnknownHostException e) %7B%0A            LOG.error(%22Unknown host exception when getting address of local host: %7B%7D%22, e.getMessage());%0A            return %22%22;%0A        %7D%0A
     

Improve localhost exception handling