From 29087cf64907063ca9c05eb19b883b0dbf294c7a Mon Sep 17 00:00:00 2001 From: Doug MacEachern Date: Fri, 11 Mar 2005 02:37:38 +0000 Subject: [PATCH] add getServiceName method --- .../src/net/hyperic/sigar/NetPortMap.java | 82 ++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/bindings/java/src/net/hyperic/sigar/NetPortMap.java b/bindings/java/src/net/hyperic/sigar/NetPortMap.java index 77c65c8e..01a9c2dd 100644 --- a/bindings/java/src/net/hyperic/sigar/NetPortMap.java +++ b/bindings/java/src/net/hyperic/sigar/NetPortMap.java @@ -1,13 +1,93 @@ package net.hyperic.sigar; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.File; +import java.io.FileReader; + import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.StringTokenizer; public class NetPortMap { + private static Map udpServices = null; + private static Map tcpServices = null; + + private static void parseServices(String type, Map services) { + File file = new File("/etc/services"); + if (!file.exists()) { + return; + } + + BufferedReader reader = null; + + try { + reader = new BufferedReader(new FileReader(file)); + String line; + while ((line = reader.readLine()) != null) { + String name, protocol; + Long port; + + line = line.trim(); + if ((line.length() == 0) || (line.charAt(0) == '#')) { + continue; + } + + StringTokenizer st = new StringTokenizer(line, " \t/#"); + if (st.countTokens() < 3) { + continue; + } + name = st.nextToken().trim(); + String pnum = st.nextToken().trim(); + protocol = st.nextToken().trim(); + if (!type.equals(protocol)) { + continue; + } + services.put(Long.valueOf(pnum), name); + } + } catch (IOException e) { + return; + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { } + } + } + } + + public static String getServiceName(String protocol, long port) { + if (protocol.equals("tcp")) { + return getTcpServiceName(port); + } + else if (protocol.equals("udp")) { + return getUdpServiceName(port); + } + else { + return String.valueOf(port); + } + } + + public static String getTcpServiceName(long port) { + if (tcpServices == null) { + tcpServices = new HashMap(); + parseServices("tcp", tcpServices); + } + return (String)tcpServices.get(new Long(port)); + } + + public static String getUdpServiceName(long port) { + if (udpServices == null) { + udpServices = new HashMap(); + parseServices("udp", udpServices); + } + return (String)udpServices.get(new Long(port)); + } + /** * Map listening tcp ports to connected remote addresses. * key == Listening tcp port on the local machine. @@ -66,6 +146,6 @@ public class NetPortMap { Long port = (Long)entry.getKey(); List addresses = (List)entry.getValue(); System.out.println(port + "=" + addresses); - } + } } }