Java preventing other network connections - java

I have a java application that does two things with an internet connection. The first is a simple port 80 connect to send some data:
try {
url = new URL(req);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(tOut);
conn.setConnectTimeout(1000);
conn.setRequestProperty("Connection", "close");
conn.setReadTimeout(urlTimeout);
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((inputLine = br.readLine()) != null) {
Line = Line + inputLine ;
}
} catch (MalformedURLException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
The second is a ssh connection that looks for information coming from the server. The connection part is:
con = SshConnector.createInstance();
transport = new SocketTransport(hostname, port);
try {
ssh = con.connect(transport, username);
} catch (Exception es) {
}
PasswordAuthentication pwd = new PasswordAuthentication();
do {
pwd.setPassword("password");
} while (ssh.authenticate(pwd) != SshAuthentication.COMPLETE
&& ssh.isConnected());
Then I loop looking for input from the server.
I have one user that is on a Verizon Jetpack. When my application is running the application runs slow, he cannot connect his VPN to his office, do a browser speed test, etc. Close my application and the VPN and browser works fine.
I do not have that problem and many others running my application are fine. Is there something I am overlooking or can change to keep from apparently shutting down his jetpack?
Tnx

Related

SocketException when there is no internet connection

I'm programming an application which opens socket in service and sends some data to server and also listens for incoming data. Problem of course appears when connection with internet is lost on android device.
Here is code snippet where i get
java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed
out)
try{
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
String s;
while((s = in.readLine())!= null){ //here error of course
...
}
mSocket.close();
}catch(Exception e){
e.printStackTrace();
}
Error is thrown when internet connection is lost and BufferedReader try to
readLine(). How to avoid this and why is it of course?
UPDATE
Error didn't bother me until I tryed to do next scenario:
1) run socket with wifi turned on
2) turn on also mobile data
3) turned off wifi
When wifi is turned off error occourse, but i'm connected to internet through mobile data, so I would like continu to listen on socket without error. Is this possible and how?
What you should do is reconnect a new socket in your catch block. The original connection is now gone, and I don't know a way of "seamlessly" swapping it.
try {
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
...
} catch(Exception e){
try {
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
...
} catch (Exception e2) {
// OK you really lost connectivity at this point, tell the user.
}
}

How to do a DNS lookup through a tor proxy with Java?

As the headline says I currently try to resolve a hostname through a tor proxy.
Tor is running on a dedicated server (192.168.1.15). Getting a website is no problem, but if I try to get the IP of the host, Java still does a direct lookup and ignores the proxy.
I already tried this ways:
//Trying lib from: www.xbill.org/dnsjava
import org.xbill.DNS.*;
[...]
public void lookup(){
//Lookup without proxy
try {
InetAddress addr = Address.getByName("stackoverflow.com");
System.out.println(addr);
} catch (UnknownHostException e) {
e.printStackTrace();
}
//set socks v5 proxy
//http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies
System.setProperty("socksProxyHost", "192.168.1.15");
System.setProperty("socksProxyPort", "9050");
//trying to resolve with dnsjava
try {
Record [] records = new Lookup("stackoverflow.com", Type.A).run();
for (Record record : records) {
System.out.println(record);
}
} catch (TextParseException e) {
e.printStackTrace();
}
//trying to resolve without lib
try {
System.out.println(InetAddress.getByName("stackoverflow.com"));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public void request(){
InetSocketAddress torProxyAddress = new InetSocketAddress("192.168.1.15", 9050);
Proxy torProxy = new Proxy(Proxy.Type.SOCKS, torProxyAddress);
Socket underlying = new Socket(torProxy);
InetSocketAddress unresolvedAdr = InetSocketAddress.createUnresolved("stackoverflow.com", 80);
try {
underlying.connect(unresolvedAdr);
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(underlying.getOutputStream()));
BufferedReader in = new BufferedReader( new InputStreamReader(underlying.getInputStream()));
out.write("GET / HTTP/1.1\nHost: stackoverflow.com\n\n");
out.flush();
String line;
while((line = in.readLine()) != null){
System.out.println(line);
}
} catch (IOException e) {
} finally {
try {
underlying.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How do I force Java to do a lookup through the tor proxy?
Doing it through a Tor proxy is hard as the InetAddressNameservice cannot be routed through Tor without modifying or implementing an own NetAddressNameService.
Normal nslookups are done through port 53 (UDP) and Tor is currently only supporting TCP.
So using the Tor-way of resolving the hostnames you need to implement your own "Tor-client" as you need to send RELAY_RESOLVE cells (check tor-spec.txt chapter 6.4)
One easy option would be to use SilverTunnel-NG.
This library also uses the Tor network for doing the ns-lookups.

Ganymed wont connect to windows in JAVA

I'm using Ganymed to run OS commands from JAVA. In Linux everything works like a charm. The problem is with Windows. I get the error: There was a problem while connecting to [IP]:[port]. I've tried to connect through localhost/router ip/internet ip and port 22/1023 and I've opened the ports on windows firewall and on the router as well.
I'm guessing the problem is that there isnt anything that listen the port like ssh in Linux. Am I right?
what do I need to do to fix that?
BTW I've looked on JSCH lib but Ganymed is much more simpler
Here's my sample code:
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String hostname = "192.168.xxx.xxx", username = "xxx", password = "xxx";
int port = 1023;
try {
Connection conn = new Connection(hostname,port);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
throw new IOException("Authentication failed.");
}
Session sess = conn.openSession();
sess.execCommand("ver");
System.out.println("Here is some information about the remote host:");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
System.out.println("ExitCode: " + sess.getExitStatus());
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
}
You should install open ssh on windows to keep the ssh server running, which would act as a listener interface for inbound connections

Testing Socket Program

So I wrote a simple Socket program that send message from Client to Server program and wanted to know what is the proper procedure to go about testing this? Both my Client and Server machines are running on Ubuntu 12.04 and I'm remote connecting to both of them.
For my Client code when I instantiate the client socket (testSocket) do I use its IP Address and Port number or Servers IP Address and Port number?
Here is the Code for Client:
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket testSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
testSocket = new Socket("192.168.0.104", 5932);
os = new DataOutputStream(testSocket.getOutputStream());
is = new DataInputStream(testSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Couldn't find Host");
}
catch (IOException e)
{
System.err.println("Couldn't get I/O connection");
}
if (testSocket != null && os != null && is != null)
{
try
{
os.writeBytes("Hello Server!\n");
os.close();
is.close();
testSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Host not found");
}
catch (IOException e)
{
System.err.println("I/O Error");
}
}
}
Here is the code for Server:
public static void main(String[] args)
{
String line = new String() ;
try
{
ServerSocket echoServer = new ServerSocket(5932);
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true)
{
line = is.readLine();
os.println(line);
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
I'm new to Sockets and not sure what I'm supposed be seeing. I compiled both programs in terminal fine but not sure which one should I be running first or do they need to be started simultaneously?
Thanks
Your server is running in a infinite loop. Avoid that.
You have to restart your computer.
while (true)
{
line = is.readLine();
os.println(line);
}
try
while (!line.equals("Hello Server!"))
{
line = is.readLine();
os.println(line);
}
Run the server first. echoServer.accept(); waits for a connection. When it gets the first connection,
http://docs.oracle.com/javase/tutorial/networking/sockets/ this is a short java tutorial on how to work with sockets and also you can learn how to make a server that would accept multiple connections at a time. This tutorial explains you always need to start the server first, which is only logical. You should use threads to manage connections and then close them so that you use resources efficiently

java.net.ConnectException: /192.168.1.106:8002 - Connection refused ( Android Exception )

I am facing this current problem now.
I am able to send command to the device and receive response from the device from android emulator to the socket.
But, when I install the same application on tablet, there is a problem. The first time I send command to check status that device is connected or not, it send me the response that device is connected but when I send command second time it throws the following exception:
java.net.ConnectException: /192.168.1.106:8002 - Connection refused.
This is the code that does the request:
public static String sendRequestandResponse(final String host,final int port,
final String command,
final int timeoutInMillis,final int responseLength) throws UnknownHostException,NetworkSettingException
{
if (host == null)
{
throw new NullPointerException("host is null"); //NOPMD
}
Socket clientSocket=null;
try {
/**
* Creating socket connection with IP address and port number to send Command
*/
try{
clientSocket = new Socket();
SocketAddress remoteAdr = new InetSocketAddress(host, port);
clientSocket.connect(remoteAdr, 1000);
clientSocket.setSoTimeout(timeoutInMillis);
}catch (Exception e) {
e.printStackTrace();
throw new NetworkSettingException(e.getMessage());
}
final PrintWriter outPutStream = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), CHARSET));
try
{
outPutStream.print(command);
outPutStream.flush();
BufferedReader responseString = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), CHARSET));
response = new StringBuilder();
try
{
int pos = 0;
while (true)
{
pos++;
System.out.println(pos);
int i=responseString.read();
byte[] resp={(byte)i};
System.out.println(new String(resp));
response.append(new String(resp));
if(pos>=responseLength){
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Log.d("ConnectionSocket", "Socket closed with break");
break;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
finally
{
responseString.close();
}
}
finally
{
outPutStream.close();
}
}
catch(IOException ex){
}
catch(NullPointerException ex){ //NOPMD
}
finally
{
try {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
} catch (NullPointerException ex) { //NOPMD
} catch (IOException ex) {
}
}
return response.toString();
}
I think it doesnt close the socket first time, so second time it refuse the connection.
The same code works on emulator though.
You will get the Connection Refused only when the server is not accepting the connection.
Mostly, the Problem is the Firewall which blocks the any untrusted incoming connection.
My application shows this message mostly when the server has a firewall which block it.
So u can add the Exception list in Firewall for your application.

Categories