Creating FTP Client in Java with java.net -Connection refused: connect - java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class FTPClient {
protected Socket sk;
protected BufferedReader in;
protected BufferedWriter out;
public static void main (String [] args){
FTPClient fc1 = new FTPClient("sitename.org",21);
fc1.Login("user", "password!");
}
FTPClient(String server, int port){
try{
this.sk = new Socket(server,port);
this.in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
this.out = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));
String response = in.readLine();
System.out.println(response);
}
catch(Exception e){
System.out.println(e);
}
}
public boolean Login(String user, String pass){
boolean success = false;
try{
sendOut("USER " + user);
sendOut("PASS " + pass);
success = true;
System.out.println("Waiting for response");
String response = in.readLine();
System.out.println(response);
}
catch(Exception e){
System.out.println("Login Failure");
success = false;
}
return(success);
}
public void sendOut(String command) throws Exception{
if (sk == null){
throw new Exception("Client is not connected!");
}
try{
out.write(command + "\r\n");
out.flush();
}
catch(Exception e){
System.out.println(e);
}
}
}
Hello, I wrote this code as a client to try to connect and login to a server with an FTP connection. However, I keep getting this error message,
java.net.ConnectException: Connection refused: connect
Can someone please help me?

You try to connect to a SSH server, hence you get the unexpected reply. The defualt FTP port is 21.

Ok... My School's server doesn't have FTP set up and opened on port 21. So, I started FTP on my server on port 21 and it properly connect now. Thanks for helping me trouble shoot guys.
Lessons learned: FTP is normally on port 21. However, if there are connection problems, one should check if the server is even listening on port 21 by logging on and using the "sudo netstat netstat -lntu" command. If FTP is not even on, one can install it by running "sudo apt-get install vsftpd".
Thanks everyone for helping me troubleshoot to the answer.

Related

Socket connection not workin in flutter release apk

I am new to working with sockets, and I am working on this project where a connection between my android flutter app and a java server is needed, to do this I am trying socket programming.
The server code is fairly simple, I create a new thread for every client connected and I give them a bunch of URLs, later on, this should be replaced by a query result. here is the java code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CrawlitServer {
// The port number on which the server will listen for incoming connections.
public static final int PORT = 6666;
//main method
public static void main(String[] args) {
System.out.println("The server started .. ");
// Create a new server socket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// Listen for incoming connections and create a new thread for each one
while (true) {
try {
new CrawlitServerThread(serverSocket.accept()).start();
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
public static class CrawlitServerThread extends Thread {
private final Socket socket;
public CrawlitServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
List<String> list = new ArrayList<>();
//assign a value to list
list.add("http://www.google.com");
list.add("http://www.yahoo.com");
list.add("http://www.bing.com");
list.add("http://www.facebook.com");
list.add("http://www.twitter.com");
list.add("http://www.linkedin.com");
list.add("http://www.youtube.com");
list.add("http://www.wikipedia.com");
list.add("http://www.amazon.com");
list.add("http://www.ebay.com");
list.add("http://stackoverflow.com");
list.add("http://github.com");
list.add("http://quora.com");
list.add("http://reddit.com");
list.add("http://wikipedia.org");
try {
// Get the input stream from the socket
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
Scanner scanner = new Scanner(inputStream);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
PrintWriter writer = new PrintWriter(outputStream, true);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println("Received Message from client: " + line);
writer.println(list + "\n");
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
Now I run this server and connect to it using sockets in Flutter, I give it the IP address I get from the ipconfig command, and here is the dart code:
import 'dart:async';
import 'dart:io';
//Utilities that manage connections with server sockets.
//ServerUtil Class
class ServerUtil {
static const port = 6666;
static const host = MY_IP_GOES_HERE;
static late Socket socket;
static bool connected = false;
//a list of urls returned by the server
static List<String> urls = [];
//Constructor
ServerUtil() {
//Initialize the socket.
Socket.connect(host, port).then((Socket sock) {
socket = sock;
connected = true;
socket.listen(dataHandler,
onError: errorHandler, onDone: doneHandler, cancelOnError: false);
//send a message to the server.
}).catchError((e) {
print("Unable to connect: $e");
});
}
//Query method that sends a message to the server. The server will return a list of urls.
//The urls will be added to the urls list.
//The urls list will be returned.
static Future<List<String>> query(String userQuery) async {
urls.clear();
//check if socket is connected.
if (connected) {
//send the query to the server.
socket.writeln(userQuery);
await Future.delayed(const Duration(milliseconds: 200));
print(urls);
return urls;
}
//if socket is not connected, wait for 5 seconds and try again.
await Future.delayed(const Duration(milliseconds: 50));
return query(userQuery);
}
//Handles data from the server.
void dataHandler(data) {
//String of received data.
String dataString = String.fromCharCodes(data).trim();
//remove first and last character from the string.
dataString = dataString.substring(1, dataString.length - 1);
//remove all the whitespace characters from the string.
dataString = dataString.replaceAll(RegExp(r'\s+'), '');
urls = dataString.split(',');
}
//Handles errors from the server.
void errorHandler(error, StackTrace trace) {
print(error);
}
//Handles when the connection is done.
void doneHandler() {
socket.destroy();
}
}
This works perfectly fine while using a debug apk running it on my real Note 9 device. The problem however is that when I build a release apk and try it out, nothing happens.
The way I set it up is that I wait for the query method in an async and then I send the result to a new screen and push that screen into the navigator.
But in the release apk nothing happens, the new screen doesn't load.
So this leads me to my first question:
Is there a way to debug a release apk? see what exceptions it throws or print some stuff to console?
I have the server running on my Laptop, and the app runs on my phone which is on the same WIFI network.
My second question is:
Do I need to enable some sort of option with my router or my laptop to allow my phone to connect? it does connect in debug mode without any modifications
I tried some random things, like using 'localhost' instead of my IP, as I would normally connect say with a java client for example, but it didn't work.
My last question is:
Does the release apk or like android OS prevent connections to local hosts, maybe because it thinks it is not secure? but then it still connects in debug mode.
Thank you for your time.

how to connect two computers over the same network using java sockets?

I am not able to connect two different machines over the same network using the following client server programs.
the code however runs fine on the same machine.
I think in the client program it goes in an infinite loop just before socket.accept();
please suggest a possible solution.
server.java
import java.io.*;
import java.net.*;
import java.lang.*;
class server{
public static void main(String args[]){
try{
int one,zero;
one=zero=0;
ServerSocket sock=new ServerSocket(2000);
Socket soc=sock.accept();
DataInputStream dis=new DataInputStream(soc.getInputStream());
System.out.println("Connection Established");
String msg =dis.readLine();
System.out.println("MESSAGE : "+msg);
for(int i=0;i<msg.length();i++){
if(msg.charAt(i)=='0')
zero++;
else
one++;
}
System.out.println("Ones are "+one);
System.out.println("Zeros are "+zero);
soc.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
client.java
import java.io.*;
import java.net.*;
class client{
public static void main(String args[]){
try{
Socket soc=new Socket("localhost",2000);//or ipv4 address for different computers
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
PrintStream pr=new PrintStream(soc.getOutputStream());
System.out.println("Enter message..");
String msg =is.readLine();
pr.println(msg);
System.out.println("YOU ENTERED.."+msg);
soc.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
I had the same problem and here is how I figured it out : UDP Broadcast. It will allow the client to connect to server regardless of its IP, so you don't have to hardcode the IP Address, only the port used for UDP (see below).
Here is how it works :
1.Server watch port n
2.Client send message at all port n he can reach
3.When a message reach server's port, Server response with to the sender and include its IP address
4.Client create a socket and connect to the IP address he got from the server
Here is the tutorial that helped me : http://michieldemey.be/blog/network-discovery-using-udp-broadcast/

Copy a Different Program's Local Server (Java)

First off, networking is not my strongest subject. So sorry if this question is ridiculous, or if I'm missing some major information. I'd be happy to provide any needed.
I am trying spoof a server program. The program I am trying to pretend to be basically creates a local server, then allows client versions of the same program to connect (provided they are on the same computer).
Using netstat -a -b -n I was able to figure out that the server was binding itself to 0.0.0.0:53640. The other information given was:
Proto: UDP
Local Address: 0.0.0.0:56426
Foreign Address: * : * (Without spaces, stackoverflow doesn't seem to like this when it doesn't have them)
State: (Was blank)
The closest I was able to come was
Proto: TCP
Local Address: 0.0.0.0:56426
Foreign Address: 0.0.0.0:0
State: LISTENING
The code that I am using is:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Main2
{
public static void main(String args[])
{
String ip = "0.0.0.0";
int port = 53640;
try
{
InetAddress address = InetAddress.getByName(ip);
ServerSocket server = new ServerSocket(port, 5, address);
System.out.println("Waiting for connection...");
Socket socket = server.accept();
System.out.println("Got connection!");
doSocket(socket);
server.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void doSocket(Socket socket)
{
try
{
System.out.println("Connection from: " + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
int b;
char c;
while ((b = in.read()) != -1)
{
c = (char) b;
System.out.print(c);
}
in.close();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
ServerSocket.accept seems to never stop yielding, as "Got connection!" is never printed to the output.
All help is very welcome. Thanks in advance! And sorry if I've done something horribly wrong with this post, its my first one.
UDP is connection-less, and 'ServerSocket' is connection-oriented and TCP-only. Have a look at the Oracle docs on datagrams (UDP).
UDP ports and TCP ports are in different namespaces; you can't get mixups from one to the other.

Problems trying to implement Java Sockets example

I am trying to implement this example here: Reading from and Writing to a Socket
I copied and pasted the code into NetBeans. I changed the port name "taranis" to "localhost" and tried to run the example, but I got the error:
run: Couldn't get I/O for the connection to: localhost. Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I also tried to substitute localhost for my actual hostname of my laptop, but it gives the similar error. Can you help pinpoint what I am doing wrong?
Edit: In regards to Mark's recommendation, when I substitute
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
with
e.printStackTrace();
I get:
run:
java.net.ConnectException: Connection refused: connect
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)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at EchoClient.main(EchoClient.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
The echo service is not listening. Why not write your own? Run the application below and change your client to connect to the same port (8000).
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private static final int PORT = 8000;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Echo server started");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("echoing: " + inputLine);
out.println(inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Btw, the next example (knock-knock server) does work and gives a nice example of using a 'protocol' class.
I don't think the echo service is running by default, when I tried a quick test it on my Win XP client, it did not work:
H:\>telnet localhost 7
Connecting To localhost...Could not open connection to the host, on port 7:
Connect failed
H:\>
So to make your code work, you could try pointing it to a server that has the echo service running.
For future reference, the echo service is commonly disabled by default. I'm using windows 7, to enable it I followed the instructions found here:
http://www.windowsnetworking.com/articles_tutorials/windows-7-simple-tcpip-services-what-how.html
Example worked fine for me afterwards.
For XP:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sag_tcpip_pro_simptcpinstall.mspx?mfr=true

Listen to port via a Java socket

A server software my client communicates with regularly sends transaction messages on port 4000. I need to print those messages to the console line by line. (Eventually I will have to write those values to a table, but I’m saving that for later.)
I tried this code but it doesn’t output anything:
package merchanttransaction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MerchantTransaction {
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket("192.168.1.104", 4000);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
By the way, I need to be able to monitor that port until the program terminates. I’m not sure if the code above will be able to do that because I don’t see any iteration to the code.
I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.
You need to use a ServerSocket. You can find an explanation here.
What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:
$ nc -l 4000
...and change socket address to localhost:4000, it will work and try to read something from nc-created server.
What you probably want is to create a ServerSocket and listen on it:
ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();
The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)
Try this piece of code, rather than ObjectInputStream.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}

Categories