ServerSocket + client Socket - how do I get IP address of client? - java

I have a ServerSocket instance which is listening for connections. When a client connects to it, I would like to get the IP of the connected socket, but can't seem to find the right method to do so.
public void start() {
listenSocket = new ServerSocket(port);
connectionSocket = listenSocket.accept();
}
I've tried calling the following with no luck:
connectionSocket.getLocalAddress();
connectionSocket.getInetAddress.getHostAddress();
listenSocket.getLocalSocketAddress();
None of the above return the correct IP. They either return "/0:0:0:0:0:0:0:1%0" or "0.0.0.0".
What am I doing wrong?

connectionSocket.getRemoteSocketAddress();

Related

Running into an java.net.BindException: Address already in use (Bind failed) on server- client socket app

I am Running into a java.net.BindException: Address already in use (Bind failed) on a server-client socket app
I am trying to learn about Java sockets using a Youtube tutorial as a reference. My code seems to match everything in the video (except variables names) but, when trying to run the server and then the client sockets, I get:
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
I have tried even printing out the local port just to make sure I connect to the right available port but, nothing works. Is there any documentation I can look into to solve this problem? or any guidance?
Server.java
public class serverSocket {
public static void main(String args[]) throws IOException{
String message, serverResponse;
ServerSocket serverSocket = new ServerSocket(56789);
System.out.print(serverSocket.getLocalPort());
Socket acceptClientRequestSocket = serverSocket.accept();
Scanner serverScanner = new Scanner(acceptClientRequestSocket.getInputStream());
message = serverScanner.next();
System.out.println(message);
serverResponse = message.toUpperCase();
PrintStream newMessage = new PrintStream(acceptClientRequestSocket.getOutputStream());
newMessage.println(serverResponse);
}
}
Client.java
public class clientSocket {
public static void main(String args[]) throws UnknownHostException, IOException {
String message,outputMessage;
Scanner clientInput = new Scanner(System.in);
Socket clientSocket = new Socket("localhost",56789);
Scanner incomingStream = new Scanner(clientSocket.getInputStream());
System.out.println("Enter a message");
message = clientInput.next();
PrintStream printClientStream= new PrintStream(clientSocket.getOutputStream());
printClientStream.println(message);
outputMessage = incomingStream.next();
System.out.println(outputMessage);
}
}
Is there any documentation I can look into to solve this problem? or any guidance?
You have probably your previously exectued program still running. Check the running java processes. Kill the the previous one and try again.
If this wouldn't help try restarting your machine. If the problem persists after that then some service is already running on this port and is starting with the OS. In that case you can either change the port number in your app or disable that service.

Java : Opening client socket

I work on a java application.
I got a java socket server mapped with a #ServerEndpoint("/wsock")
Form my javascript code I access the WebSocket from this URL :
ws://192.9.200.73:8084/socketserver/wsock
I want now access to this socket from my java code. But how can I specify the address "socketserver/wsock" ? I've tried something but I got every time an error message.
This is my test :
Socket s = new Socket("localhost/socketserver/wsock", 8084);
But it doesn't work, I got everytime an error message: ".UnknownHostException: localhost/socketserver/wsock"
Any idea?
Thank's
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
Try this. Its something like ping. If you get true its connected. But your server should be ready.
You use a Websocket client. You can't use a Socket directly for this. There is a superimposed protocol.

python socket server and java android socket - freezes app

I'm making a python server running on my computer and java socket client running on my phone. the minute the java tries to connect, the app freezes. Not saying anything in the logcat. I have no idea why...
python 3.5.1:
PORT = 8888
import socket
sock = socket.socket()
sock.bind(("0.0.0.0", PORT))
sock.listen(1)
client = None
while not client:
try:
client = sock.accept()
except:
pass
print(client[1])
java:
static String get_leaderboard() {
Socket sock;
OutputStream out;
InputStream in;
try {
System.out.println("now trying to connect");
sock = new Socket("192.168.1.29", 8888);
System.out.println("connected successfuly");
out = sock.getOutputStream();
in = sock.getInputStream();
return Integer.toString(in.read());
} catch (IOException e) {
e.printStackTrace();
}
return "Error in connection";
but actually, logcat never prints "connected successfuly". just "trying to connect".
This line is wrong:
client = sock.connect()
Servers don't call connect(). Servers call listen() and accept(). Only clients call connect().
Since your server calls bind() and listen(), but not accept(), any client will hang trying to connect to it.
Resources:
https://wiki.python.org/moin/TcpCommunication
https://docs.python.org/3/howto/sockets.html
http://beej.us/guide/bgnet/

Issue connecting a client to localhost using Java

I'm trying to setup a protected client and protected server connection using sockets. Whenever I run the program I receive a connection error saying the connection was refused. I'm using Java in Eclipse IDE running on MAC OS. Any ideas why this code cannot connect to my localhost?
Protected Client:
public static void main(String[] args) throws Exception
{
String host = "localhost";
int port = 7999;
String user = "George";
String password = "abc123";
Socket s = new Socket(host, port);
ProtectedClient client = new ProtectedClient();
client.sendAuthentication(user, password, s.getOutputStream());
s.close();
}
Protected Server
public static void main(String[] args) throws Exception
{
int port = 7999; //7999
ServerSocket s = new ServerSocket(port);
Socket client = s.accept();
ProtectedServer server = new ProtectedServer();
if (server.authenticate(client.getInputStream()))
System.out.println("Client logged in.");
else
System.out.println("Client failed to log in.");
s.close();
}
When I run the program I receive the following error:
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:431)
at java.net.Socket.connect(Socket.java:527)
at java.net.Socket.connect(Socket.java:476)
at java.net.Socket.<init>(Socket.java:373)
at java.net.Socket.<init>(Socket.java:216)
at ProtectedClient.main(ProtectedClient.java:36)
I have gotten this error before when using particular sockets. Try a different socket like 5687. (Or if you need that particular socket, try making sure your firewall allows it).
Make sure you call client.close() on the server as well. If your program worked once it might be blocking that port.

Java Networking "Connection Refused: Connect"

I have been trying to get a simple networking test program to run with no results.
Server:
import java.io.*;
import java.net.*;
public class ServerTest {
public static void main(String[] args) {
final int PORT_NUMBER = 44827;
while(true) {
try {
//Listen on port
ServerSocket serverSock = new ServerSocket(PORT_NUMBER);
System.out.println("Listening...");
//Get connection
Socket clientSock = serverSock.accept();
System.out.println("Connected client");
//Get input
BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
System.out.println(br.readLine());
br.close();
serverSock.close();
clientSock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Client:
import java.io.*;
import java.net.*;
public class ClientTest {
public static void main(String[] args) throws IOException {
final int PORT_NUMBER = 44827;
final String HOSTNAME = "xx.xx.xx.xx";
//Attempt to connect
try {
Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
//Output
out.println("Test");
out.flush();
out.close();
sock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program works just fine when I use 127.0.0.1 or my internal IP for the hostname. But whenever I switch to my external IP address, it throws a java.net.ConnectException: Connection refused: connect error.
I purposely picked such an uncommon port to see if that was the problem, with no luck.
I can connect with no problems using telnet, but when I try to access the port with canyouseeme.org, it tells me the connection timed out.
I even tried to disable all firewalls and antivirus including the Windows default ones and the router firewall, with all ports forwarded and DMZ enabled, and it still says that the connection timed out. I use Comcast as my ISP, and I doubt that they block such a random port.
When I use a packet tracer, it shows TCP traffic with my computer sending SYN and receiving RST/ACK, so it looks like a standard blocked port, and no other suspicious packet traffic was going on.
I have no idea what is going on at this point; I have pretty much tried every trick I know. If anyone know why the port might be blocked, or at least some way to make the program work, it would be very helpful.
These problem comes under the following situations:
Client and Server, either or both of them are not in network.
Server is not running.
Server is running but not listening on port, client is trying to connect.
Firewall is not permitted for host-port combination.
Host Port combination is incorrect.
Incorrect protocol in Connecting String.
How to solve the problem:
First you ping destination server. If that is pinging properly,
then the client and server are both in network.
Try connected to server host and port using telnet. If you are
able to connect with it, then you're making some mistakes in the client code.
For what it's worth, your code works fine on my system.
I hate to say it, but it sounds like a firewall issue (which I know you've already triple-checked) or a Comcast issue, which is more possible than you might think. I'd test your ISP.
Likely the server socket is only being bound to the localhost address. You can bind it to a specific IP address using the 3-argument form of the constructor.
I assume you are using a Router to connect to Internet. You should do Port Forwarding to let public access your internal network. Have a look at How do you get Java sockets working with public IPs?
I have also written a blog post about Port forwarding, you might wanna have a look :) http://happycoders.wordpress.com/2010/10/03/how-to-setup-a-web-server-by-yourself/
But I still couldn't get this accessed over public IP, working on it now...
I had the same problem because sometimes the client started before server and, when he tried to set up the connection, it couldn't find a running server.
My first (not so elegant) solution was to stop the client for a while using the sleep method:
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
I use this code just before the client connection, in your example, just before Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
My second solution was based on this answer. Basically I created a method in the client class, this method tries to connect to the server and, if the connection fails, it waits two seconds before retry.
This is my method:
private Socket createClientSocket(String clientName, int port){
boolean scanning = true;
Socket socket = null;
int numberOfTry = 0;
while (scanning && numberOfTry < 10){
numberOfTry++;
try {
socket = new Socket(clientName, port);
scanning = false;
} catch (IOException e) {
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
return socket;
}
As you can see this method tries to create a socket for ten times, then returns a null value for socket, so be carefull and check the result.
Your code should become:
Socket sock = createClientSocket(HOSTNAME, PORT_NUMBER);
if(null == sock){ //log error... }
This solution helped me, I hope it helps you as well. ;-)

Categories

Resources