Check what ports are being used
How can I check at whi开发者_开发知识库ch ports there is a service running of a certain ip address. ( code in java please)
Edit: My prof asks "Every time the program discovers a running service it has to print the message". From that, I thought he wants me to find out what ports are being used. However, I just asked him again. And he told me that I just need to detect a a port which is free (not being used).
So, I think I solve my problem. Thanks for help.
InetAddress addr = InetAddress.getByName("hostName");
Socket socket = new Socket(addr, 8090);
The hit/trial idea would be to try different ports. If the above code snippet doesn't thrown an exception then the host is accepting connections on that port. If it isn't you'll see an exception, typically ConnectException. I am not suggesting thats an ideal way to go about it but it's just an option.
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.
Try using the netstat command in your command prompt. You can type netstat -h to see help, but it appears that netstat -b will show processes running.
If you mean running a Java program on a computer to check that computer's port availability, look at this.
Checking port availability in Java
If you mean using a Java program to get port information from a remote computer, good luck. You could try connecting to different ports and checking which ones refuse the connection.. but that's a terrible idea.
You are going to either have to execute a command line argument(like netstat) from within java or port scan. The port scan will also detect ports that you can't listen on even if they are not in use. Your system may disallow port 443 unless you are root, for example.
Something like:
for(int port=0; port<65536; port++)
{
try
{
new ServerSocket(port);
System.out.println("Successfully listend on port " + port);
//clean up socket here
}
catch (IOException e)
{
System.out.println("Could not listen on port " + port);
}
}
精彩评论