Firewall and FTP Directory Listing in C#
I am trying to get a directory listing of an FTP site but am having issues connecting and retrieving the listing. I believe the problem开发者_StackOverflow中文版 is with the windows firewall for Windows 2008 Server R2. Here is the code:
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.UsePassive = false;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("user", "pass");
request.Proxy = HttpWebRequest.DefaultWebProxy;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Label1.Text = reader.ReadToEnd();
reader.Close();
response.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
I am wondering what firewall settings or ports need to be opened to allow this action to happen. I enabled all incoming/outgoing traffic on ports 21 and 20 and that didn't work so I allowed all traffic incoming/outgoing for all ports and that worked. However, opening up every port like that is not a viable solution :)
I don't think this is really suited to StackOverflow, because this question moreso pertains to security configuration for Windows Server 2008 R2. But, in light, I tested your code, and it works just fine, so you need to make a Windows Firewall exception for FTP access on the server for the required FTP ports. Otherwise, Windows Firewall will indeed block your incoming connections from your client. If opening a Firewall Exception does not fix the issue then you will want to investigate other security configuration concerns on your server.
I finally figure it out. You need to create a custom inbound traffic rule in Windows Firewall around the w3p process. Here is a walkthrough.
Create a new Rule in Inbound traffic Select Custom
Select “This Program Path”
Find the w3wp.exe service (usually in Windows\System32 folder)
Click Customize
Select “Apply to services only”
Change the Protocol Type to TCP
Set local and remote ports to “All Ports” (you can try to narrow it down to only port 21, but that doesn't always work, especially with asynchronous uploads)
Select any IP address for local IP addresses (or a range if you know the local IP address range)
Select “These IP addresses” for remote IP addresses and click Add. Enter the IP address of the FTP site you will be uploading too
Click OK once you have added the FTP IP address, then click Next
Select Allow the Connection
Apply rule to Domain, Private and Public
Name is “Allow incoming TCP w3wp.exe traffic from port 21”
Click finish
精彩评论