从端口号获取服务名称

get service name from port number

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.*;
import java.util.*;

public class Abc{
    public static void main(String arg[]){
        try
        {
            String hostname = InetAddress.getLocalHost().getHostName();
            for (int port = 1; port <= 1024; port++) 
            {
                try 
                {
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress("localhost", port), 1000);
                    socket.close();
                    System.out.println("Port "+ port +" is open");
                    Process p1=Runtime.getRuntime().exec("grep -w $port /etc/services"); 
                    p1.waitFor(); 
                    BufferedReader reader=new BufferedReader(new InputStreamReader(p1.getInputStream())); 
                    String line=reader.readLine(); 
                    while(line!=null)  
                    { 
                       System.out.println(line); 
                       line=reader.readLine(); 
                    }
                }catch(Exception e3){} 
            }
        }catch(Exception e2){} 
    }
}

上面的代码给出了给定端口号的服务名称....但是当给定端口变量时它不起作用。

grep -w 443 /etc/services     //working
grep -w $port /etc/services    // not working

$port 变量中没有值。 上面的代码有没有修改?

Port 是在java 中定义的字符串变量,因此在unix 中不会通过将其视为shell 变量来解析。你可以这样做:

Process p1=Runtime.getRuntime().exec("grep -w " + port + " /etc/services"); 

或者您可以在发出 grep 命令之前设置端口(如 "port= "+ port + " && grep...." ),这与上面类似。