Reputation: 1
The following function successfully returns the FTP server's welcome message when the input IP address is valid.
When I test it with something that has the format of an IP address but doesn't correspond to an FTP server, I get a WebException that is thrown from System.dll, and not from the function. The WebException takes a very long time to get caught, and I would like to avoid relying on try-catch if possible.
How would I fix this so when I pass in an invalid IP address, CheckIP returns "Timeout" (or finishes execution in some other way) instead of dealing with the exception?
Note: I'm aware that connections can be tested with Ping, I just wanted to know if there's a way to do it natively within FTP.
public string CheckIP(string ip){
string respStr="Timeout";
try
{
var connection = (FtpWebRequest)WebRequest.Create(@"ftp://" + ip + @"/");
connection.Credentials = new NetworkCredential(Username, Password);
connection.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
connection.Timeout = 500;
var response = (FtpWebResponse)connection.GetResponse();
respStr = response.WelcomeMessage.ToString();
response.Close();
}
catch (Exception)
{
respStr = "Exception";
}
return respStr;
}
Upvotes: 0
Views: 143