View Javadoc
1   /*
2    * Copyright 2017-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.software.os.unix.freebsd;
6   
7   import static com.sun.jna.platform.unix.LibCAPI.HOST_NAME_MAX;
8   
9   import org.slf4j.Logger;
10  import org.slf4j.LoggerFactory;
11  
12  import com.sun.jna.Native;
13  
14  import oshi.annotation.concurrent.ThreadSafe;
15  import oshi.jna.ByRef.CloseablePointerByReference;
16  import oshi.jna.platform.unix.CLibrary;
17  import oshi.jna.platform.unix.CLibrary.Addrinfo;
18  import oshi.jna.platform.unix.FreeBsdLibc;
19  import oshi.software.common.AbstractNetworkParams;
20  import oshi.util.ExecutingCommand;
21  
22  /**
23   * FreeBsdNetworkParams class.
24   */
25  @ThreadSafe
26  final class FreeBsdNetworkParams extends AbstractNetworkParams {
27  
28      private static final Logger LOG = LoggerFactory.getLogger(FreeBsdNetworkParams.class);
29  
30      private static final FreeBsdLibc LIBC = FreeBsdLibc.INSTANCE;
31  
32      @Override
33      public String getDomainName() {
34          try (Addrinfo hint = new Addrinfo()) {
35              hint.ai_flags = CLibrary.AI_CANONNAME;
36              String hostname = getHostName();
37  
38              try (CloseablePointerByReference ptr = new CloseablePointerByReference()) {
39                  int res = LIBC.getaddrinfo(hostname, null, hint, ptr);
40                  if (res > 0) {
41                      if (LOG.isErrorEnabled()) {
42                          LOG.warn("Failed getaddrinfo(): {}", LIBC.gai_strerror(res));
43                      }
44                      return "";
45                  }
46                  Addrinfo info = new Addrinfo(ptr.getValue()); // NOSONAR
47                  String canonname = info.ai_canonname.trim();
48                  LIBC.freeaddrinfo(ptr.getValue());
49                  return canonname;
50              }
51          }
52      }
53  
54      @Override
55      public String getHostName() {
56          byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1];
57          if (0 != LIBC.gethostname(hostnameBuffer, hostnameBuffer.length)) {
58              return super.getHostName();
59          }
60          return Native.toString(hostnameBuffer);
61      }
62  
63      @Override
64      public String getIpv4DefaultGateway() {
65          return searchGateway(ExecutingCommand.runNative("route -4 get default"));
66      }
67  
68      @Override
69      public String getIpv6DefaultGateway() {
70          return searchGateway(ExecutingCommand.runNative("route -6 get default"));
71      }
72  }