tags:

views:

239

answers:

5

I am trying to write an FTP client using java.

As far as I understand I need to send my IP adress with PORT command when I need to establish an active connection but, How do I get that IP address?

I am trying to do something like this but it is obviously wrong:

ServerSocket ssock = new ServerSocket();
ssock.bind(null);
ssock.ssock.getLocalPort();
ssock.getInetAddress();

Last line returns null.

So again how can I send my IP address and port to server?

Thank you.

A: 

Is using of the PORT command a fixed requirement?

With PORT you open a local port and listen on it.
Then you send that port number to the server and it connects with you.
That can cause problems when the client is behind a router and also with some firewalls.

Because of that many clients use the PASV command.
In this case the server sends you a portnumber and you can connect to it.

David R
+1  A: 

The server socket will accept connection from any IP address. So, if your machine's normal IP address is 1.2.3.4, it will accept connections on 1.2.3.4 and 127.0.0.1. You need to specify an actual IP address to use. For normal use of ftp, I guess you can get this from the local address of your control channel socket. Addresses can also be taken from java.net.NetworkInterface, although you then have the problem of deciding on the correct interface.

Tom Hawtin - tackline
+1  A: 

To get your IP address you could try

ssock.getHostName()

which will return a String that will be your hostname or the IP.

jschoen
A: 

Getting the local address from other socket (the one that I use to connect ftp server at the first place) seems to work.

socket.getLocalAddress();

Thank You.

prometeus
+2  A: 

You need to connect first, then call the socket.getLocalAddress() to get the correct local address. When you have multiple IPs, you only know the correct address to reach a specific destination after connection is established.

Sun JRE comes with a FTP client sun.net.ftp.FtpClient. You can check out how they do it.

With wide-spread use of NAT and proxies, PORT command rarely works. You should try passive mode first. As you can see, Sun's client only does PORT when PASV fails.

ZZ Coder