View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.software.os.unix.aix;
6   
7   import static com.sun.jna.platform.unix.LibCAPI.HOST_NAME_MAX;
8   
9   import com.sun.jna.Native;
10  
11  import oshi.annotation.concurrent.ThreadSafe;
12  import oshi.jna.platform.unix.AixLibc;
13  import oshi.software.common.AbstractNetworkParams;
14  import oshi.util.Constants;
15  import oshi.util.ExecutingCommand;
16  import oshi.util.ParseUtil;
17  
18  /**
19   * AixNetworkParams class.
20   */
21  @ThreadSafe
22  final class AixNetworkParams extends AbstractNetworkParams {
23  
24      private static final AixLibc LIBC = AixLibc.INSTANCE;
25  
26      @Override
27      public String getHostName() {
28          byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1];
29          if (0 != LIBC.gethostname(hostnameBuffer, hostnameBuffer.length)) {
30              return super.getHostName();
31          }
32          return Native.toString(hostnameBuffer);
33      }
34  
35      @Override
36      public String getIpv4DefaultGateway() {
37          return getDefaultGateway("netstat -rnf inet");
38      }
39  
40      @Override
41      public String getIpv6DefaultGateway() {
42          return getDefaultGateway("netstat -rnf inet6");
43      }
44  
45      private static String getDefaultGateway(String netstat) {
46          /*-
47          $ netstat -rnf inet
48          Routing tables
49          Destination        Gateway           Flags   Refs     Use  If   Exp  Groups
50          *
51          Route Tree for Protocol Family 2 (Internet):
52          default            192.168.10.1      UG        9    873816 en0      -      -
53          127/8              127.0.0.1         U         9    839480 lo0      -      -
54          192.168.10.0       192.168.10.80     UHSb      0         0 en0      -      -   =>
55          192.168.10/24      192.168.10.80     U         3    394820 en0      -      -
56          192.168.10.80      127.0.0.1         UGHS      0         7 lo0      -      -
57          192.168.10.255     192.168.10.80     UHSb      2      7466 en0      -      -
58          */
59          for (String line : ExecutingCommand.runNative(netstat)) {
60              String[] split = ParseUtil.whitespaces.split(line);
61              if (split.length > 7 && "default".equals(split[0])) {
62                  return split[1];
63              }
64          }
65          return Constants.UNKNOWN;
66      }
67  }