Reputation: 1860
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
Upvotes: 1
Views: 1202
Reputation: 9795
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()
.
Upvotes: 2