简体   繁体   中英

Java : Socket connections with simple Blacklist

So i'm making a simple client-server application in Java. As simple as it gets, i think, and i'm trying to implement a blacklist.txt that has several IP Addresses that will be refused to connect if any of the IP's there match the IP trying to connect to the Socket. I'm kind of new at this, but here's what I got:

ServerSocket server = new ServerSocket(6500);
    System.out.println ("Server Started on port 6500");     
    while (true){//Waiting clients
        Socket socket = null;
        BufferedReader reader = new BufferedReader(new FileReader("C:\\UNIV\\Redes\\workspace\\Copy of Ex_4.3_Teste\\lists\\blacklist.txt"));
        String line = null;
        socket = server.accept();

        while ((line = reader.readLine()) != null) {
            if (line == socket.getInetAddress().toString()) {
                 System.out.println("IP Blacklisted: " + socket.getInetAddress().toString());
                 socket.close(); //Refusing connection
            }
            System.out.println("Line: " + line); //Just checking if reading OK
            System.out.println("Socket: " + socket.getInetAddress().toString()); //Just checking if reading OK

        }

        System.out.println("New connection..");

        Thread t = new Thread(new EchoClientThread(socket));                             
        t.start();          
    }       
}

Then I start a thread for each connecting client, but I think that's not relevant to what i'm asking.

The whole idea is to refuse connecting if the IP Address is equal to any line of the blacklist.txt

I clearly have something wrong here, because it's not working, can someone point me in the right direction please ?

Much appreciated.

EDIT: Forgot the contents of blacklist.txt:

/192.168.2.200
/127.0.0.1

I put the slashes before the IPs because I noticed the output from socket.getInetAddress().toString() was /IP.IP.IP.IP

Change this line

if (line == socket.getInetAddress().toString()) {

to

if (line.equals(socket.getInetAddress().toString())) {

Strings are objects (not primitive types like int , float , char ) and should be compared with .equals() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM