Reputation: 13395
I'm trying to check whether several pors are open and if 80 port is open - send http request and then show result in console. Every port is checked in his own thread.
I send requests like this
public static void send(Socket sock, String host) throws IOException{
PrintWriter pw = new PrintWriter(sock.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: " + host);
pw.println("");
pw.flush();
}
In class TCPClient
I use it and return result as bytes and then show it console.
try {
sock = new Socket(host, port);
System.out.println("port " + port + " is in use");
// send request
HttpSender.send(sock, host);
BufferedReader bf = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuffer response = new StringBuffer();
String line = "";
while((line = bf.readLine()) != null) {
response.append(line);
response.append('\r');
}
bf.close();
return String.valueOf(response).getBytes(); // in method run I show it
} catch (SocketException e) {
return ("port " + port + " is free").getBytes();
}
I create pool of threads for port checking.
public class ThreadPool {
private static int MAX_THREADS = 5;
private static String DESTINATION = "http://stackoverflow.com/";
private ExecutorService es = null;
public ThreadPool() {
es = Executors.newFixedThreadPool(MAX_THREADS);
}
public void perform(int start, int end) throws UnknownHostException {
for (int i = start; i <= end; i++) {
Runnable req = new TCPClient(DESTINATION, i);
es.execute(req);
}
es.shutdown();
while (!es.isTerminated()) {
}
;
System.out.println("all ports checked!");
}
}
When I set destination as www.stackoverflow.com
and got document with text that it was moved permanently to http://stackoverflow.com/
. When I set this destination - I've got UnknownhostException
.
Where is the problem?
Upvotes: 0
Views: 280
Reputation: 3863
Have you tried private static String DESTINATION = "stackoverflow.com";
? The string "http://stackoverflow.com"
isn't a hostname, it's a URL.
Upvotes: 2