FTPWebRequest - Active Mode with specific port - c#

I would like to connect to a FTP-Server which works in the 'active-mode'. This means, the client can send the port number, on which the data-connection should be done. Usually this is a random port. (N > 1023)
In our case, it would be really nice, if we could always use a specific port for the connection to the FTP-Server. Something like '8232'.
Is this possible?
This is my code:
FtpWebRequest.DefaultWebProxy = null;
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + "OurDomainOfTheFTP" + "/"));
ftpWebRequest.Credentials = new NetworkCredential(this.benutzer, this.passwort);
ftpWebRequest.Timeout = 5000;
ftpWebRequest.UsePassive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse webResponse = ftpWebRequest.GetResponse();
webResponse.Close();
Can i just write something like that?
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + "OurDomainOfTheFTP" + ":8232/"));

Unfortunately the port you supply to FtpWebRequest.Create is the command port, not the data port. In your initial example the port is omitted, causing it to default to 21.
It seems FtpWebRequest does not support specifying a port number for the data connection, see this link.
This thread contains some alternative FTP (and other protocols) clients that perhaps are able to specify this.

Related

How to read data from Mettler Toledo IND560 via Ethernet using C# socket

I'm trying to connect to Mettler Toledo IND560 scale device using c# application. Everything work fine in RS-232 connection, but it's not with Ethernet.
Following intruction in Mettler Toledo technical guide, i used HyperTerminal (port 1701) but no luck with that. It alway show connection error.
The same with C# application (Exception: No connection could be made because the target machine actively refused it 192.168.1.xx:1701).
private const int PORT_NUMBER = 1701;
private const string cmd = "user admin";
try
{
TcpClient client = new TcpClient();
client.Connect("192.168.1.11",PORT_NUMBER); //Error here
Stream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
StreamReader reader = new StreamReader(stream);
if (client.Connected)
{
Console.WriteLine("Connected to Mettler Toledo IDN560");
Console.WriteLine("Sending command: {0}\\n", cmd);
writer.Write($" {cmd}" + '\n');
writer.Flush();
Thread.Sleep(1000);
string str = reader.ReadLine();
Console.WriteLine(str);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
Expected respone from device is <12 ACCESS OK> but it is not.
What is wrong here ?!
In IND560 Terminal User’s Guide it says "The InSite™ configuration tool program is used to flash new terminal softwarethrough the COM1 serial port or Ethernet port." Have you tried to connect with this program?
in my case i'm using a IND780. The command sequence is:
user USERNAME
pass PASSWORD
After both commands you can now read the weight, for example:
READ wt0101 wt0102
I've used this library:
https://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library

C# Win Form App and FTP connection

I'm creating a Windows Form Application (C#) that connects to the FTP server, using Visual Studio 2013 Express.
Problem: The remote server returned an error: (530) Not logged in.
Notes:
no problems connecting to the server using primary FTP account;
determined that the problem is caused by # symbol in the ftpUser;
tried replacing ftpUser and ftpPW with the values;
host - GoDaddy - unlike primary account, all secondary FTP accounts need to have #example.com in their username;
verified, using FileZilla, that the secondary account credentials are correct;
in point 5), noticed in FileZilla log, Server does not support non-ASCII characters - even though it connects/transfers files without problems;
Below you will find the code that I'm using:
//Set Host, User and Password for the FTP;
string ftpHost = "ftp.example.com";
string ftpUser = "user#example.com";
string ftpPW = "passw0rd";
string ftpFullPath = #"ftp://" + ftpHost + ftpfilepath;
//Establish a connection to the server;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpFullPath);
ftp.Credentials = new NetworkCredential(ftpUser, ftpPW);
ftp.KeepAlive = true;
ftp.UseBinary = true;
I'm wondering if the server is translating the proxy as username#host (i.e. user#example.com#ftp.example.com;
I apologize in advance if I made any mistakes in the lingo. I'm fairly new to programming.
You are missing the separation folder char (usually / or //) so the FTP server can index the file you want to get. Change this line and try with:
string ftpFullPath = #"ftp://" + ftpHost + "/" ftpfilepath;
Or
string ftpFullPath = #"ftp://" + ftpHost + "//" ftpfilepath;
Or (better way if available):
string ftpFullPath = #"ftp://" + Path.Combine(ftpHost, ftpfilepath);

portforwarding in c# (matter with NATUPNPlib)

hi guys i use code below to forward port 9090 to my laptop
NATUPNPLib.UPnPNAT upnpnat = new NATUPNPLib.UPnPNAT();
NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;
mappings.Add(9090, "TCP", 9090, "192.168.1.104", true, "ProApp-SHARE");
and this code for firewall permission
string command = "netsh http add urlacl url=http://" + "192.168.1.104" + ":" + "9090" + "/ user=everyone";
StreamWriter ns = new StreamWriter(Application.StartupPath + #"\fw.bat", false);
ns.WriteLine(command);
ns.Close();
Process n = new Process();
n.StartInfo.FileName = Application.StartupPath + #"\fw.bat";
if (System.Environment.OSVersion.Version.Major >= 6)
{
n.StartInfo.Verb = "runas";
}
n.Start();
when i do this i can access my local website that runs on 192.168.1.104:9090 from internet , but after 30 seconds up to 1 minute its just disabled , and i have to run these codes again, can some one help me with this???
UPnP is notoriously badly implemented in most routers. You might want to try using a different UPnP library to perform the port map. Check out Open.NAT.

Responde to "no Ident response" on IRC

I'm writing a IRC client in c# and I always get "No ident response" message and the it just disconnects.
Code
TcpClient client = new TcpClient(args[0], port);
sock.Connect(serverEndPoint);
NetworkStream stream = client.GetStream();
NetworkStream streamw = client.GetStream();
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
System.IO.StreamWriter writer = new System.IO.StreamWriter(streamw);
writer.WriteLine("loaloaloa");
IPEndPoint rep = (IPEndPoint)sock.LocalEndPoint;
while (true)
{
string bytes = reader.ReadLine();
Console.WriteLine("Received: {0}", bytes);
if (String.IsNullOrEmpty(bytes))
break;
}
Here's the message
:kornbluth.freenode.net NOTICE * :*** Looking up your hostname...
:kornbluth.freenode.net NOTICE * :*** Checking Ident
:kornbluth.freenode.net NOTICE * :*** Found your hostname
:kornbluth.freenode.net NOTICE * :*** No Ident response
ERROR :Closing Link: 127.0.0.1 (Connection timed out)
I figured out that i have to listen on port 113 to get a message and then respond with the same message and little bit more info.
So my question is how do i start listening on port 113, and how would i accept the message and responde?.
as #Miserable_Variable already linked to, you need an ident service running on tcp:113
on that port you will receive a connection from the IRCd that will give you something like
"xxxxx, 6667" where xxxxx is the portnumber of the IRC connection on your side and obviously 6667 is the portnumber on the side of the IRCd ...
if you reply with "xxxxx, 6667 : USERID : UNIX : yyyyy" where yyyyy stands for your username and xxxxx for the requested port number, the IRCd should accept your connection (unless you caught yourself a ban ...)

Set Port number when using FtpWebRequest in C#

I keep getting a exception when I try to FTP to my Win 2008 Server from C# code using VS2008 as debugger.
My test class looks like this:
public class FTP
{
private string ftpServerIP = "192.168.10.35:21";
private string ftpUserID = "Administrator";
private string ftpPassword = "XXXXXXXX";
private string uploadToFolder = "uploadtest";
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + uploadToFolder + "/" + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
When I execute the code I get a Connection Failed with FTP error 227 in the GetRequestStream() call.
In the exception I can see the connection fails to: 192.168.10.35:52184
I have no idea how it comes up with port 52184.
I specify in the ftpServerIP that it should be port 21.
I have found a few persons with the same issues on google but I haven't found a good example on how this is solved and I still don't understand why it happens.
Anyone know how to handle this issue??
UPDATE:
I have tried to connect to a different FTP account and there it all works fine. Therefore I tested my 192.168.10.35:21 FTP but it works fine in CuteFTP Pro and the likes.
This just makes it even more strange..
My guess would be Windows firewall issues, FTP uses other ports than just port 21 - sometimes changing the FTP mode from active to passive helps to get things working.
reqFTP.UsePassive = false;
Look at this good article on FTP: Active FTP vs. Passive FTP, a Definitive Explanation
Thies got it right, it had to do with passive mode
The fix in the code is so insanely simple :)
reqFTP.UsePassive = false;
And it worked fast and without errors!
It is important to differentiate the COMMAND port and the DATA port. The connection protocol will also change depending if you are in ACTIVE or PASSIVE mode.
ACTIVE MODE :
1) The client initiate a connection from a random unspecified COMMAND port (N > 1023) to the default server COMMAND port (21). The client will specify his DATA port (N+1) and start listening on this port.
2) The server initiate a connection from his default DATA port (20) to specified client DATA port (N+1).
PASSIVE MODE :
1) The client initiate a connection from a random unspecified COMMAND port (N > 1023) to the default server COMMAND port (21) with the PASSIVE command. The server open a random DATA port (P > 1023) and send it to the client.
2) The client initiate a connection from his DATA port (N+1) to the specified server DATA port (P > 1023).
If you use ACTIVE mode, you will most likely need to let your client's firewall accept the connection from the server to your port (N+1 > 1024).
In your example, you were in ACTIVE mode. Your client initiated a connection from his COMMAND port (52183) to the server's default COMMAND port (21) and specified its DATA port (52184 = 52183 + 1). Then the server initiated a connection from its default DATA port (20) to the client's DATA port (52184) which was most likely rejected by the client's firewall.
I hope this helps you solve your problem!

Categories