从端口号获取服务名称

时间:2015-01-20 13:06:26

标签: java sockets service port

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){} 
    }
}

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

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

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

1 个答案:

答案 0 :(得分:4)

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

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

或者你可以在发出grep命令之前设置端口(比如“port =”+ port +“&amp;&amp; grep ....”),这与上面的相似。