I am trying to pass data to a telnet server. I get the initial prompt for login credentials but it won't take the username. I need to pass the username, wait for a password prompt and enter that. Then be able to send and receive data, keeping the socket open at all times.
my code looks like this(its rough as I am trying it in the console first)
try
{
client = new TcpClient("10.0.0.94",23);
Console.WriteLine("Connected to server.");
}
catch (SocketException)
{
Console.WriteLine("Failed to connect to server");
return;
}
//Assign networkstream
NetworkStream networkStream = client.GetStream();
byte[] data = new byte[1024];
int size = networkStream.Read(data, 0, data.Length);
recieved = Encoding.ASCII.GetString(data, 0, size);
Console.WriteLine(recieved);
if (recieved.Contains("login"))
{
string loginrx;
string cmd = string.Format("{0}\r",user) ;
byte[] writeBuffer = Encoding.ASCII.GetBytes(cmd);
networkStream.Write(writeBuffer, 0, writeBuffer.Length);
byte[] logindata = new byte[1024];
int loginsize = networkStream.Read(logindata, 0, logindata.Length);
loginrx = Encoding.ASCII.GetString(logindata, 0, loginsize);
Console.WriteLine(loginrx);
Console.ReadLine();
}
I get the login prompt, but it all stops there.
any help would be great.
One Send does not equal once receive. You need some way to tell that you are at the "end of a message" (likely a newline). See Message Framing for some learning materials.
You will need to consult the telnet protocol but likely you need to would need keep reading till you read in a newline before checking the text you got. You may want to use a var sr = new StreamReader(networkStream, Encoding.ASCII)
with sr.ReadLine()
to read in your strings instead of manually calling networkStream.Read
and using Encoding.ASCII.GetString
to decode.