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){}
}
}
The above code gives the service name for a given port no.... but it doesnt work when the port variable is given.
上面的代码给出了给定端口号的服务名称....但是当给出端口变量时它不起作用。
grep -w 443 /etc/services //working
grep -w $port /etc/services // not working
there is no value in the $port variable. Is there any modification for the above code?
$ port变量中没有值。上面的代码有什么修改吗?
1 个解决方案
#1
4
Port is a string variable defined in java, so won't be resolved in unix by treating it as a shell variable. You could do it as:
Port是java中定义的字符串变量,因此不会通过将其视为shell变量在unix中解析。你可以这样做:
Process p1=Runtime.getRuntime().exec("grep -w " + port + " /etc/services");
OR you could set the port before issuing grep command (like "port= "+ port + " && grep...." ) which is similar to above.
或者您可以在发出grep命令之前设置端口(如“port =”+ port +“&& grep ....”),这与上面的类似。
#1
4
Port is a string variable defined in java, so won't be resolved in unix by treating it as a shell variable. You could do it as:
Port是java中定义的字符串变量,因此不会通过将其视为shell变量在unix中解析。你可以这样做:
Process p1=Runtime.getRuntime().exec("grep -w " + port + " /etc/services");
OR you could set the port before issuing grep command (like "port= "+ port + " && grep...." ) which is similar to above.
或者您可以在发出grep命令之前设置端口(如“port =”+ port +“&& grep ....”),这与上面的类似。