The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made

senzacionale picture senzacionale · Apr 25, 2010 · Viewed 14.2k times · Source

System.Net.WebException: The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.
at System.Net.FtpWebRequest.CheckError()
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.Net.CommandStream.Abort(Exception e)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetRequestStream()
at BackupDB.Program.FTPUploadFile(String serverPath, String serverFile, FileInfo LocalFile, NetworkCredential Cred) in D:\PROJEKTI\BackupDB\BackupDB\Program.cs:line 119

code:

FTPMakeDir(new Uri(serverPath + "/"), Cred);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath+serverFile);
request.UsePassive = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = Cred;
byte[] buffer = new byte[10240];    // Read/write 10kb

using (FileStream sourceStream = new FileStream(
    LocalFile.ToString(), FileMode.Open))
{
    using (Stream requestStream = request.GetRequestStream())
    {
        int bytesRead;
        do
        {
            bytesRead = sourceStream.Read(buffer, 0, buffer.Length);
            requestStream.Write(buffer, 0, bytesRead);
        } while (bytesRead > 0);
    }
    response = (FtpWebResponse)request.GetResponse();
    response.Close();
}

Answer

MikeTeeVee picture MikeTeeVee · Oct 12, 2012

omg. What's up with all the pandering here for buying their 3rd party solutions instead of informing you to change one line of code?

Try toggling the Passive value to see which works:

    request.UsePassive = false;

This may depend on the firewall between the Machines (client and server).

I've noticed if I go through our firewall, then I need it left at True, otherwise it will return the Exception:

The remote server returned an error: (500) Syntax error, command unrecognized.

However, if I'm behind the firewall (like two machines connecting directly to each other within a data-center) then I need to set it to False, otherwise it will return the Exception:

The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.

If this works and you want to make your solution more adaptable, you could wrap your request in a try-catch block using the default True value, and if you get the 500 error, then switch UsePassive to False and try it again.