View Javadoc
1   /*
2    * Copyright 2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.driver.unix;
6   
7   import static org.hamcrest.MatcherAssert.assertThat;
8   import static org.hamcrest.Matchers.anyOf;
9   import static org.hamcrest.Matchers.greaterThanOrEqualTo;
10  import static org.hamcrest.Matchers.startsWith;
11  
12  import org.junit.jupiter.api.Test;
13  import org.junit.jupiter.api.condition.DisabledOnOs;
14  import org.junit.jupiter.api.condition.EnabledOnOs;
15  import org.junit.jupiter.api.condition.OS;
16  
17  import oshi.software.os.InternetProtocolStats.IPConnection;
18  import oshi.software.os.InternetProtocolStats.TcpStats;
19  import oshi.software.os.InternetProtocolStats.UdpStats;
20  import oshi.util.tuples.Pair;
21  
22  @DisabledOnOs(OS.WINDOWS)
23  class NetStatTest {
24  
25      @DisabledOnOs({ OS.WINDOWS, OS.MAC, OS.LINUX })
26      @Test
27      void testQueryNetstat() {
28          for (IPConnection conn : NetStat.queryNetstat()) {
29              assertThat("Connection is tcp or udp", conn.getType(), anyOf(startsWith("tcp"), startsWith("udp")));
30          }
31      }
32  
33      @EnabledOnOs({ OS.MAC, OS.FREEBSD })
34      @Test
35      void testQueryTcpNetstat() {
36          Pair<Long, Long> tcpConns = NetStat.queryTcpnetstat();
37          assertThat("ipv4 connections must be nonnegative", tcpConns.getA().intValue(), greaterThanOrEqualTo(0));
38          assertThat("ipv6 connections must be nonnegative", tcpConns.getB().intValue(), greaterThanOrEqualTo(0));
39      }
40  
41      @EnabledOnOs(OS.LINUX)
42      @Test
43      void testQueryStatsLinux() {
44          TcpStats tcpStats = NetStat.queryTcpStats("netstat -st4");
45          assertThat("tcp connections must be nonnegative", tcpStats.getConnectionsEstablished(),
46                  greaterThanOrEqualTo(0L));
47          UdpStats udp4Stats = NetStat.queryUdpStats("netstat -su4");
48          assertThat("udp4 datagrams sent must be nonnegative", udp4Stats.getDatagramsSent(), greaterThanOrEqualTo(0L));
49          UdpStats udp6Stats = NetStat.queryUdpStats("netstat -su6");
50          assertThat("udp4 datagrams sent must be nonnegative", udp6Stats.getDatagramsSent(), greaterThanOrEqualTo(0L));
51      }
52  
53      @EnabledOnOs(OS.OPENBSD)
54      @Test
55      void testQueryStatsOpenBSD() {
56          TcpStats tcpStats = NetStat.queryTcpStats("netstat -s -p tcp");
57          assertThat("tcp connections must be nonnegative", tcpStats.getConnectionsEstablished(),
58                  greaterThanOrEqualTo(0L));
59          UdpStats udpStats = NetStat.queryUdpStats("netstat -s -p udp");
60          assertThat("udp  datagrams sent must be nonnegative", udpStats.getDatagramsSent(), greaterThanOrEqualTo(0L));
61      }
62  }