0

I read some materials about ServerSocket and tried to listen on port 80 and print for example InetAddress of website which I was opening in web browser but my program couldn't do this. My code:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Site implements Runnable {
    private int port;
    Site(int port){
        this.port = port;
    }
    public void run() {
        try {
            ServerSocket server = new ServerSocket(port);
            while(true){
                Socket socket = server.accept();
                System.out.println(socket.getInetAddress());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String args[]){
        Thread thread = new Thread(new Site(80));
        thread.start();
    }
}

When I run my program I am only one time in the while loop and the program doesn't print System.out.println(socket.getInetAddress()) and as the result when I open my web browser and visit http sites I don't see any output. Do you know what I am doing wrong? Do you know any other ways to print InetAddress for currently open website? Any materials will by appreciate.

Kabun
  • 35
  • 3
  • What are you trying to do here? I don't get it. – qwerty_so Mar 04 '15 at 23:01
  • Your program looks like it ought to work. What happens when you run it? Do you get any exceptions? – Kenster Mar 04 '15 at 23:09
  • 1
    'Couldn't do it' isn't a problem description. Post the error, exception, stack trace, unexpected behaviour, whatsover it is. Edit it into your question. NB you do need to close accepted sockets. – user207421 Mar 04 '15 at 23:51
  • After you start it, how specifically are you testing it? – Kenster Mar 05 '15 at 17:14
  • I insert two `System.out.println("test")` between `Socket socket = server.accept() ` and there something goes wrong because the second output doesn't print or maybe I think wrong. – Kabun Mar 05 '15 at 18:06

1 Answers1

1

I can't comment without proper reputation so forgive me for throwing everything out here:
you might already have something listening on port 80
you might be running on a version of linux that restricts non root process binding to ports above 1024
you might be blocked by a software firewall

Brian
  • 11
  • 2