1
2
3
4
5 package oshi.software.common;
6
7 import java.net.InetAddress;
8 import java.net.UnknownHostException;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.List;
12 import java.util.Locale;
13
14 import oshi.annotation.concurrent.ThreadSafe;
15 import oshi.software.os.NetworkParams;
16 import oshi.util.FileUtil;
17 import oshi.util.ParseUtil;
18
19
20
21
22 @ThreadSafe
23 public abstract class AbstractNetworkParams implements NetworkParams {
24
25 private static final String NAMESERVER = "nameserver";
26
27 @Override
28 public String getDomainName() {
29 InetAddress localHost;
30 try {
31 localHost = InetAddress.getLocalHost();
32 } catch (UnknownHostException e) {
33 localHost = InetAddress.getLoopbackAddress();
34 }
35 return localHost.getCanonicalHostName();
36 }
37
38 @Override
39 public String getHostName() {
40 InetAddress localHost;
41 try {
42 localHost = InetAddress.getLocalHost();
43 } catch (UnknownHostException e) {
44 localHost = InetAddress.getLoopbackAddress();
45 }
46 String hn = localHost.getHostName();
47 int dot = hn.indexOf('.');
48 if (dot == -1) {
49 return hn;
50 }
51 return hn.substring(0, dot);
52 }
53
54 @Override
55 public String[] getDnsServers() {
56 List<String> resolv = FileUtil.readFile("/etc/resolv.conf");
57 String key = NAMESERVER;
58 int maxNameServer = 3;
59 List<String> servers = new ArrayList<>();
60 for (int i = 0; i < resolv.size() && servers.size() < maxNameServer; i++) {
61 String line = resolv.get(i);
62 if (line.startsWith(key)) {
63 String value = line.substring(key.length()).replaceFirst("^[ \t]+", "");
64 if (value.length() != 0 && value.charAt(0) != '#' && value.charAt(0) != ';') {
65 String val = value.split("[ \t#;]", 2)[0];
66 servers.add(val);
67 }
68 }
69 }
70 return servers.toArray(new String[0]);
71 }
72
73
74
75
76
77
78
79
80 protected static String searchGateway(List<String> lines) {
81 for (String line : lines) {
82 String leftTrimmed = line.replaceFirst("^\\s+", "");
83 if (leftTrimmed.startsWith("gateway:")) {
84 String[] split = ParseUtil.whitespaces.split(leftTrimmed);
85 if (split.length < 2) {
86 return "";
87 }
88 return split[1].split("%")[0];
89 }
90 }
91 return "";
92 }
93
94 @Override
95 public String toString() {
96 return String.format(Locale.ROOT,
97 "Host name: %s, Domain name: %s, DNS servers: %s, IPv4 Gateway: %s, IPv6 Gateway: %s",
98 this.getHostName(), this.getDomainName(), Arrays.toString(this.getDnsServers()),
99 this.getIpv4DefaultGateway(), this.getIpv6DefaultGateway());
100
101 }
102 }