I have to write a little command line FTP client for linux in C. It works quite well for common uses (directory managing, retrieving and storing files, etc.), and I want to add the active mode (at the moment every transfer is made under passive mode).
I know that I have to send a command in the shape of :
PORT a,b,c,d,e,f
where a b c d are the ip address blocks and e f the port numbers. However, as I understand it, the ip has to be the ip of the machine on which my client is running, but I’ve been advised to use getsockname(). From what I’ve tested, getsockname() gets me the local ip of the interface(s) used by my socket, not my ip seen from the internet. So I can’t give this ip address for the server to connect.
The question is : am I understanding the command PORT correctly, and how to get the correct ip to send it ?
FTP active mode means that a server opens a connection to a client and sends data ifself. It’s often unpractical, so the passive mode was invented: server opens an additional port which listens for incoming connections and starts transmission when someone is connected.
So, a passive mode session looks like this:
Whereas an example of an active session:
P.S. FTP is a very old protocol (definition from circa 1970), defined when there were no routers, gates and other transport level goodies, usually there were several machines, directly connected, so the active mode worked quite well, the passive mode is how the protocol survives today.
So, yes, you’ve gotten PORT command right, but there’s no uniform way to get your external IP (there may be several your IPs in several different networks on local machine, there may be several gates with their own networks on the way to server, which one do you want to use?). The second part of the question, how to get your IP as it is seen by server, can’t be answered (that’s what the passive mode is for).