public int getServiceByName(String tcpipService, String tcpipClass) {
int port = -1;
try {
String line;
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"/etc/services")));
while (((line = br.readLine()) != null)
&& (port == -1)) {
if ((line.length() != 0)
&& (line.charAt(0) != '#')) {
port = parseServicesLine(line,
tcpipService, tcpipClass);
}
}
br.close();
return (port);
} catch (IOException ioe) {
return -1;
}
}
private int parseServicesLine(String line,
String tcpipService) {
StringTokenizer st = new
StringTokenizer(line, " \t/#");
if (! st.hasMoreTokens()) {
return -1; // error
}
String name = st.nextToken().trim();
if (! st.hasMoreTokens()) {
return -1; // error
}
String portValue = st.nextToken().trim();
// Return port number, if name on this line matches:
if (name.equals(tcpipService)) {
try {
return (Integer.parseInt(portValue));
} catch (NumberFormatException nfe) {
return -1;
}
} else {
return -1;
}
}
The above code snippet searches the /etc/inet/services file against a service-name and returns the port-number.