Hi Humberto,
As you're probably aware, using active mode means that rather than setting
up a Socket to read from a port that is determined by the FTP Server, and
sent to you as a reply to the "PASV" command, you decide what port to use,
and use the "PORT" command to tell the server what port to send or receive
on.
The IP address is not a problem, I'm sure, so first, of course, you need
to pick a port to use. The FTP standard defines this as an "ephemeral"
port. There is some disagreement concerning what ports are "ephemeral.,"
but your best bet is to use a port between 49152 through 65535. These are
defined by IANA as the "Dynamic or Private" ports, which cannot be
registered. See
http://www.iana.org/assignments/port-numbers for more
information.
However, there is a problem here, as Windows by default only allows use of
ports 102 - 5000. While this can be reconfigured through the System
Registry, you probably don't want to do that unless necessary, especially
if you expect this app to run on any machine. The good news is, your port
can be picked for you.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
// Let the port be selected for you
IPHostEntry localHostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint localEndPoint = new IPEndPoint(localHostEntry.AddressList[0],
0);
socket.Bind(localEndPoint);
// Queue up to 5 connections
socket.Listen(5);
Next, you need to construct the PORT command. First you need the IP
address and Port number that the Socket is bound to:
int port = ((IPEndPoint)socket.LocalEndPoint).Port;
IPAddress ipAddress = ((IPEndPoint)socket.LocalEndPoint).Address;
Next, you need to construct your PORT command and send it via your Control
Socket. The format is:
h1,h2,h3,h4,p1,p2
The first four are easy. They are the 4 octets of your IPAddress. The 2
port numbers are 2 bytes that make up the port number. Fortunately, you
can get all of these from the IPAddress in your IPEndPoint. Just use the
IPAddress.GetAddressBytes method to do so:
byte[] addressBytes = localEndPoint.Address.GetAddressBytes();
StringBuilder command = new StringBuilder("PORT ");
for (int i = 0; i < addressBytes.Length; i++)
{
command.Append((short)bytes
);
command.Append(",");
}
Then you just send the command on the Control Socket, and wait for the 200
repsonse.
--
HTH,
Kevin Spencer
Microsoft MVP
Professional Numbskull
Hard work is a medication for which
there is no placebo.
Humberto Alvarez said:
Hi
Does someone know how to create a socket to connect to a ftp server that
does not accept passive connections?
I need to modify my ftp class (wich works pretty good in passive mode) to
connect to the ftp in active mode.
Thanks a lot for the help
Humberto