【问题标题】:get service name from port number从端口号获取服务名称
【发布时间】:2015-01-20 13:06:25
【问题描述】:
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 变量中没有值。 上面的代码有修改吗?

【问题讨论】:

    标签: java sockets service port


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-09-01
      • 2012-06-22
      • 2020-11-25
      • 1970-01-01
      • 2012-10-31
      • 2013-01-17
      • 2014-08-10
      • 1970-01-01
      • 2012-08-13
      相关资源
      最近更新 更多