SocketException on remote server - java

I have a problem when trying to connect to a remote server.
SocketException: Invalid argument or cannot assign requested address
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
Here is how i create the socket
if (socket == null) {
socket = new Socket();
try {
socket.setReuseAddress(true);
socket.setTcpNoDelay(true);
} catch (SocketException ex) {
}
}
dstAddress = new InetSocketAddress(server, dstPort);
srcAddress = new InetSocketAddress("localhost", srcPort);
socket.bind(srcAddress);
socket.connect(dstAddress);
Everything works fine on localhost.

http://comments.gmane.org/gmane.comp.finance.moneydance.general/5389
This sometimes occurs on other platforms - it used to occasionally
occur on earlier versions of Mac OS X. The solution definitely lies
outside of Moneydance since MD is requesting (through Java) to open a
standard network connection and the system is saying that it is unable to do so.
The only solution I have found for this is to reboot your computer.
If you are also running other software that uses a lot of network
resources, try not running that for a while to see if it makes a
difference.

Remove the bind() call. It is not required.

Try running your program with
-Djava.net.preferIPv4Stack=true
when connecting to the remote system.

Related

How to create a ServerSocket Object without the localhost address

Hy guys, my code here to create a simple server works fine with the local host address(127.0.0.1). Here is my code.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args)
{
Zig z = new Zig();
z.start();
}
}
class Zig
{
ServerSocket ss = null;
InetAddress ia = null;
Socket s = null;
private static final int prt = 56540;
Zig()
{
try
{
byte[] addr = {127,0,0,1};
ia = InetAddress.getByAddress(addr);
SocketAddress sa = new InetSocketAddress(ia,prt);
ss = new ServerSocket();
ss.bind(sa);
s = ss.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Zig start()
{
try
{
InputStream i = s.getInputStream();
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = null;
while (str != "stp")
{
str = br.readLine();
System.out.println(str);
}
br.close();
isr.close();
i.close();
s.close();
ss.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return this;
}
}
My question is, how can I use the router's IP - 192.168.8.1 instead of 127.0.0.1? I also tried the IP address from http://whatsmyip.org but still got this exception:
java.net.BindException: Cannot assign requested address: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.bind(ServerSocket.java:329)
at Zig.<init>(Main.java:26)
at Main.main(Main.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Exception in thread "main" java.lang.NullPointerException
at Zig.start(Main.java:38)
at Main.main(Main.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I wanted to create a simple server with that i can access remotely with another computer both having internet connection.
Or is there a way I can make communication between two computers over internet?
Regards.
how can I use the router's IP - 192.168.8.1
You cannot use the router's IP. You should use the IP thats available in the system.
Note this error :
> java.net.BindException: Cannot assign requested address: JVM_Bind
The bind is failing because the address isn't that of the system.
If you want your 2 devices to communicate via LAN (local network) you can use the addresses your router assigned to these devices (that's the 192.168.8.X address you mentioned. EDIT: As Prabhu mentioned, use the devices IP Address, not the routers IP-Address! You can usually find the IPs your router assigned to connected devices in your routers admin-interface). Remember that your router might assign a different adress to the same devices in the future. Most routers come with a function that always assigns the same IP to a specific device. Also, some routers block communication between local devices (i.e. between wired and WiFi devives) for security reasons. Check your router's configuration for more information and configuration options!
If you want your devices to connect via internet you have to use your routers global IP-address (thats probably the one you found out using whatsmyip).
Additionally, your router usually just blocks incoming requests from the internet for security reasons. Again, your Router probably has a function called Port forwarding, which allows you to redirect requests to a specific device (and a specific port at that device) in your local network. Use this with care, as this opens (a part) of your routers built-in security mechanisms.
Finally, depending on your provider, you may have a IPv4 address (see Wikipedia) that you share with other customers (So called DS-Lite (Wiki). In this case, you're network is not reachable from the IPv4-internet at all and your only chance is to use the IPv6 Protocol (if available).
Hope that helps.

How to kill open server sockets under windows7?

I wrote a simple server client socket program and when I recompile the server I get:
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
Therefore my question is how to kill the socket under windows 7? Is there a possible solution to kill it in eclipse?
I appreciate your answer!!
Kill the jvm this fixed the issue when I ran into it. Are you closing the socket in your code before you stop your simple server?
Like RGdev I assume that you still have a javaw process running in the background which keeps the connection open. But it could also be a different server program on your machine which hogs the port you want to use.
You can find out which processes are listening to which port with the netstat command in the cmd shell. The following parameters list (a) all connections including servers, (b) shows the executable which opened the connection and (n) suppresses the substitution of port numbers with service names for well-known ports.
netstat -abn
Here is my code for server side:
import java.io.*;
import java.net.*;
public class ServerSide {
public static void main(String[] args) {
try
{
ServerSocket myServerSocket = new ServerSocket(9999);
System.out.println("Server is waiting on host" + InetAddress.getLocalHost().getCanonicalHostName() + "port= "+ myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintStream myOutput = new PrintStream(skt.getOutputStream());
String buf = myInput.readLine();
System.out.println("Server readLine");
if(buf!=null)
{
System.out.println("Buf = " + buf);
myOutput.print("Got it?");
}
else
{
System.out.println("Nothing returned in server sidex`x ");
}
skt.close();
System.out.println("Server shutdown");
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Whooops");
}
}
}
As you can see for clean-up I've written:
skt.close();
But maybe this is not your problem, Maybe your problem is which I had 1 hour ago ;) I used to run a program but the result is not what I expected so I modify it and run it again but the port was busy or already in use! What I do on eclipse? Under the Console where you get the error, on the right side of the window there is red colour rectangle button! It say "Terminate". If you click on that your port will be free. By the way don't forget to check the console for both(Server/Client) sides.
You can also get this error message, when the process already terminated. TCP has a time wait state. This state is used to ensure that no TCP packets from an old connection can be delivered to a new process listening at the same port. Normally you should use the ServerSocket.setRuseAddress(true) to avoid this issue.

Java socket blocks on connection to a server

I am trying to connect to server using a Java socket. I am trying to connect from port 80 to 90
int port;
Socket clientsocket;
String hostname = "www.google.com";
for(port = 80;port<=90; port++){
try{
clientsocket = new Socket(hostname,port);
System.out.println("Connection at port " + port + "\t" + clientsocket.isConnected());
clientsocket.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
When I try to connect to any website like google.com or w3schools.com my program hangs on the socket() call for port numbers except 80.
Since those websites are not serving on ports 81-90 it should raise exception but instead it gets blocked. For port 80 it works fine.
When I try to connect to the apache server installed on my machine, it doesn't block for any port number and gives me Connection refused error which is the obvious behavior.
So why is it happening. Thanks in advance.
When I try to connect to any website like google.com or w3schools.com my program hangs on the socket() call for port numbers except 80. Since those websites are not serving on ports 81-90 it should raise exception but instead it gets blocked.
This is almost certainly not Java's doing.
When you invoke the Socket(String, int) constructor, the JVM asks the OS to attempt to establish a connection to the IP address corresponding to the supplied name, using the supplied port number. Assuming that we're talking TCP/IP, the OS sends off a TCP 'SYN' message, and waits for a response:
If the response is a 'SYN-ACK', it proceeds to establish the connection as per the protocol; see http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment.
If the response is an 'RST' (reset), the connect fails and this results in a Java "connection refused" exception. (This is typically what happens if the 'SYN' makes it to the remote server, only to discover that there is no application "listening" on the port you tried to connect on.)
If the response is an ICMP message of some kind (e.g. ICMP destination unreachable), this typically results in an immediate failure of the connection request, and a Java exception.
If there is no response, the OS tries again, and again, and again. Depending on the Java default connect timeout (or the explicit timeout), this process could continue for a long time.
So what is most likely happening is that something is filtering the 'SYN' messages on funky ports, and simply throwing them away. It could be the local firewall software on your PC, firewall software in your gateway, or your ISP's network, or software in the remote system you are attempting to talk to. Or this could be happening to the 'SYN-ACK' message coming back.
Either way, the blocking / timeout behavior is inherent to TCP/IP networking, and it is impossible to accurately diagnose at either the OS or Java levels. You simply need to adjust your expectations. (Or set a shorter connect timeout ...)
For this case, and any case:
/**
* Create end point and initialize connection with custom timeout for refused or server offline
*/
try{
InetSocketAddress endPoint = new InetSocketAddress(serverAddress, portNumber);
Socket socket = new Socket();
socket.connect(endPoint, 10000);
} catch(Exception e){
//... Handle connection error
}

Java Networking: Connection refused - Yes, my server is running

I'm getting following error when my client tries to connect to my server socket:
java.net.ConnectException: Connection refused: connect
But, my server is really running, on the same machine. I try to connect to it by using the external IP of my router. But when I try to connect with "localhost", it works. And, yes I did port forwarding correcly in my router. Even canyouseeme.org can connect to my server (The site says: "success" and in my server-log appears that someone connected with the server.)
So, is it for one or another reason impossible to connect to the same machine (or to a machine in the same network) via an external IP? Or is this something typical for Windows? (Normally, I use Linux)
I also tried to completely disable Windows Firewall.
ServerSocket:
public ServerSocket ssocket;
public List<ClientHandler> handlers;
public Server(int port) { // Constructor
try {
ssocket = new ServerSocket(port);
this.handlers = new ArrayList<ClientHandler>();
IpSharingManager.uploadData(Utilities.getPublicIp(), port);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
Client:
public InvisibleClient(String host, int port) {
try {
System.out.println("Trying to connect to " + host + ":" + port);
this.host = host;
this.socket = new Socket(host, port);
this.bis = new BufferedInputStream(this.socket.getInputStream());
this.bos = new BufferedOutputStream(this.socket.getOutputStream());
this.console = new RemoteConsole(this.socket);
initializeCommunication();
System.out.println("Successfully connected!");
new Thread(this, "Client Thread").start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("No server available");
}
}
Thanks
Some routers doesn't allow the internal network to connect to the external IP address of the router.
You can try to use telnet to connect to your server socket. If telnet isn't able to establish a connection, it's likely a networking problem.
Add the java.exe process and the port to your firewall exception list?
edit: Just read you already tried that. All I can suggest is make sure the network is not blocking that port. (routers)
Have You tried running it with JVM option: java.net.preferIPv4Stack=true ?
For what I see in your code, you missed the part where you accept the conection, after instantiating the server socket you need ssocket.accept() to accept conections and then you have to start reading the outputstrem from the socket

Java Socket Returns True

I hope you can help. Im fairly new to progamming and Im playing around with java Sockets.
The problem is the code below. for some reason commSocket = new Socket(hostName, portNumber); is returning true even when it has not connected with the server (server not implemented yet!). Any ideas regarding this situation?
For hostName Im passing my local machine IP and for port a manually selected port.
public void networkConnect(String hostName, int portNumber){
try {
networkConnected = false;
netMessage = "Attempting Connection";
NetworkMessage networkMessage = new NetworkMessage(networkConnected, netMessage);
commSocket = new Socket(hostName, portNumber);
// this returns true!!
System.out.println(commSocket.isConnected());
networkConnected = true;
netMessage = "Connected: ";
System.out.println("hellooo");
} catch (UnknownHostException e){
System.out.println(e.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
Many thanks.
EDIT: new Socket(.., ..); is blocking isnt it? i thought in that case if that was processed without exceptions then we have a true connection?
EDIT: I played around with anti virus and now it is working!
Had that exact same situation a few days ago on a corporate computer, and searched for it for hours.
Check your antivirus, some antivirus (like E*** N**32) use live TCP scanning that make a connection succeed even if nothing is listening on the target port but will reset it later when you try to read/write from the socket.
Add this to your code:
commSocket.getOutputStream().write(0);
commSocket.getInputStream().read();
If you get a SocketException now, you should really consider to change your antivirus.
Alternatively, set a breakpoint in your application right after creating the socket, and then use netstat -ano (on Windows) to check which process id is associated with the other endpoint of your socket (which should be on your machine if you connect to localhost).
I would suggest you to disable your antivirus, but in some cases even that does not help to unload their broken live TCP scanning driver...
The Socket constructor connects right away and will throw an IOException if it doesn't succeed. So apparently you have connected successfully to a server (this could be one you didn't make yourself).

Categories