2017-12-08 6 views
0

내가 때까지 인터넷으로 탐색 할 때 나는 SIGAR 라이브러리Java | SIGAR : 얻기 네트워크 트래픽

import java.util.*; 
import java.util.Map.Entry; 

import org.hyperic.sigar.NetFlags; 
import org.hyperic.sigar.NetInterfaceConfig; 
import org.hyperic.sigar.NetInterfaceStat; 
import org.hyperic.sigar.Sigar; 
import org.hyperic.sigar.SigarException; 

public class NetworkBandwidth { 

    private Map<String, Long> rxCurrentMap = new HashMap<String, Long>(); 
    private Map<String, List<Long>> rxChangeMap = new HashMap<String, List<Long>>(); 
    private Map<String, Long> txCurrentMap = new HashMap<String, Long>(); 
    private Map<String, List<Long>> txChangeMap = new HashMap<String, List<Long>>(); 
    private List<String> msg; 
    private Sigar sigar; 
    private String TAG = "LOG: ", serverCode; 
    private volatile boolean stopGettingNetworkBandwidth = false; 
    private ChannelHandlerContext ctx; 

    public NetworkBandwidth(String serverCode, ChannelHandlerContext ctx){ 
     this.sigar = new Sigar(); 
     this.serverCode = serverCode; 
     this.ctx = ctx; 
     this.msg = new ArrayList<>(); 
     try { 
      getMetric(); 
      System.out.println(TAG + "NETWORK INFO: " + networkInfo()); 
     } catch (SigarException e) { 
      System.out.println(e.toString()); 
     } 

    private Long[] getMetric() throws SigarException { 
     for (String ni : sigar.getNetInterfaceList()) { 
      // System.out.println(ni); 
      NetInterfaceStat netStat = sigar.getNetInterfaceStat(ni); 
      NetInterfaceConfig ifConfig = sigar.getNetInterfaceConfig(ni); 
      String hwaddr = null; 
      if (!NetFlags.NULL_HWADDR.equals(ifConfig.getHwaddr())) { 
       hwaddr = ifConfig.getHwaddr(); 
      } 
      if (hwaddr != null) { 
       long rxCurrenttmp = netStat.getRxBytes(); 
       saveChange(rxCurrentMap, rxChangeMap, hwaddr, rxCurrenttmp, ni); 
       long txCurrenttmp = netStat.getTxBytes(); 
       saveChange(txCurrentMap, txChangeMap, hwaddr, txCurrenttmp, ni); 
      } 
     } 
     long totalrx = getMetricData(rxChangeMap); 
     long totaltx = getMetricData(txChangeMap); 
     for (List<Long> l : rxChangeMap.values()) 
      l.clear(); 
     for (List<Long> l : txChangeMap.values()) 
      l.clear(); 
     return new Long[] { totalrx, totaltx }; 
    } 

    private static long getMetricData(Map<String, List<Long>> rxChangeMap) { 
     long total = 0; 
     for (Entry<String, List<Long>> entry : rxChangeMap.entrySet()) { 
      int average = 0; 
      for (Long l : entry.getValue()) { 
       average += l; 
      } 
      total += average/entry.getValue().size(); 
     } 
     return total; 
    } 

    private static void saveChange(Map<String, Long> currentMap, 
            Map<String, List<Long>> changeMap, String hwaddr, long current, 
            String ni) { 
     Long oldCurrent = currentMap.get(ni); 
     if (oldCurrent != null) { 
      List<Long> list = changeMap.get(hwaddr); 
      if (list == null) { 
       list = new LinkedList<Long>(); 
       changeMap.put(hwaddr, list); 
      } 
      list.add((current - oldCurrent)); 
     } 
     currentMap.put(ni, current); 
    } 

    private String networkInfo() throws SigarException { 
     String info = sigar.getNetInfo().toString(); 
     info += "\n"+ sigar.getNetInterfaceConfig().toString(); 
     return info; 
    } 

    public void stopGettingNetworkBandwidth(boolean stop){ 
     stopGettingNetworkBandwidth = stop; 
    } 

    public void getBandwidth() throws SigarException, InterruptedException { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       while (true){ 
        try{ 
         Long[] m = getMetric(); 
         long totalrx = m[0]; 
         long totaltx = m[1]; 
         System.out.print("totalrx(download): "); 
         System.out.println("\t" + Sigar.formatSize(totalrx)); 
         System.out.print("totaltx(upload): "); 
         System.out.println("\t" + Sigar.formatSize(totaltx)); 
         System.out.println("-----------------------------------"); 
         Thread.sleep(1000); 
        }catch (SigarException e){ 
         System.out.println(TAG + "Failed to get Network Bandwidth, SigarException >> " + e.toString()); 
        }catch (InterruptedException e){ 
         System.out.println(TAG + "Failed to get Network Bandwidth, InterruptedException >> " + e.toString()); 
        } 
        if (stopGettingNetworkBandwidth)break;if (stopGettingNetworkBandwidth)break; 
       } 
      } 
     }).start(); 
    } 

} 

내가 비록 내가 네트워크 트래픽을 얻고의 도움으로 자바에서 아래의 코드를 사용하여 네트워크 트래픽을 얻으려고 나는 예상치 못한 결과를 얻고 있다는 것을 알고 있습니다.

LAN 내부에서 통신하는 서버 및 클라이언트 응용 프로그램을 개발 중이며, 위의 코드를 사용하지 않았거나 인터넷을 검색하지 않았지만 응용 프로그램이 LAN 내부에서 통신 중이므로 0이 결과로 나왔습니다. 항상 결과를 얻었 어.

인터넷 사용법을 알아볼 수있는 방법은 무엇입니까? except when the Server and Client is sending or receiving message inside the LAN?

+0

인터넷 (다른 네트워크 연결) 또는 인터넷 (공용 인터넷)을 의미합니까? 호스트는 구성된 네트워크 마스크를 사용하여 IP 주소와 대상의 트래픽을 마스킹하여 트래픽이 동일한 네트워크에 있는지 확인합니다. 결과가 같으면 트래픽은 로컬 네트워크를 대상으로합니다. 결과가 다르면 호스트는 구성된 게이트웨이 (라우터)로 트래픽을 전송합니다. 아마도 당신이 묻고있는 것만 큼 가까이있을 것입니다. –

+0

나는 공중 인터넷을 의미합니다. . . – Polar

+0

결과가 다른지 여부를 나타내는 조건문. 그것을 시도하게하십시오. – Polar

답변

0

덕분에 Ron Maupin에게 감사드립니다.

여기,

내가 대역폭하지만, 네트워크 트래픽을 찾고되지 않았 음을 깨달았다
public void getTraffic() throws SigarException, InterruptedException { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 

       long oldReceived = 0, oldSend = 0, newReceived, newSend; 

       while (true){ 
        try{ 

         Long[] m = getMetric(); 

         newReceived = m[0]; 
         newSend = m[1]; 

         if(oldReceived != newReceived || oldSend != newSend){ //if the result is different from the previous 

          oldReceived = newReceived; //put the new result to old result 
          oldSend = newSend; //put the new result to old result 

          if(oldReceived > 999 || oldSend > 999 && oldReceived == 0 || oldSend == 0){ 
           System.out.print("totalrx(download): "); 
           System.out.println("\t" + Sigar.formatSize(newReceived)); 
           System.out.print("totaltx(upload): "); 
           System.out.println("\t" + Sigar.formatSize(newSend)); 
           System.out.println("-----------------------------------"); 
          } 

         } 
         Thread.sleep(1000); 
        }catch (SigarException e){ 
         System.out.println(TAG + "Failed to get Network Traffic, SigarException >> " + e.toString()); 
        }catch (InterruptedException e){ 
         System.out.println(TAG + "Failed to get Network Traffic, InterruptedException >> " + e.toString()); 
        } 
        if (stopGettingNetworkBandwidth)break;if (stopGettingNetworkBandwidth)break; 
       } 
      } 
     }).start(); 
    } 

, 그 결과를 관찰 한 후, 나는 getBandWidth()getTraffic()에 방법을 변경 그것을

해결 방법 나는 내 ServerClient이 로컬 네트워크 내에서 데이터를 송수신 할 때 그 결과가 천 개가 안되며 결과를 탐색하거나 다운로드 할 때 수천 또는 그 이상이라는 결과를 얻었습니다.

신뢰할 수있는 솔루션인지 확실하지 않지만 그 동안에는 두 번째 옵션을 찾을 때까지이 솔루션을 사용하게 될 것입니다.