Does NetworkStream with StreamWriter behave differently on Linux?

Viewed 183

The following console app works fine on Windows but when I run it in WSL or as a Linux Docker container I get a timeout from the server.

using System;
using System.IO;
using System.Net.Sockets;

namespace ClientTest
{
    class Program
    {
        static void Main(string[] args)
        {
            const string server = "inbound-smtp.us-west-2.amazonaws.com";
            const int port = 25;
            Console.WriteLine($"Connecting to: {server}");
            using (var client = new TcpClient(server, port))
            {
                using (NetworkStream stream = client.GetStream())
                using (StreamReader clearTextReader = new StreamReader(stream))
                using (StreamWriter clearTextWriter = new StreamWriter(stream) { AutoFlush = true })
                {
                    // read connection response
                    var connectResponse = clearTextReader.ReadLine();
                    Console.WriteLine(connectResponse);

                    // send command
                    Console.WriteLine($"HELO domain.com");
                    clearTextWriter.WriteLine("HELO domain.com");

                    // read command response
                    var commandResponse = clearTextReader.ReadLine();
                    Console.WriteLine(commandResponse);

                }
            }
        }
    }
}

Output on Windows with 250 success...

Output on Linux with 451 Timeout...

However, If I change the server address to ASPMX.L.GOOGLE.com for example then the app works as expected on Windows and Linux.

Windows

Linux

The console app is targeting .net5.0 but have also tried it with .net3.1 and got the same results. I have also tried running it on a Linux VM with Docker in the cloud but also got the same results.

Are there differences with StreamWriter/NetworkStream on Linux (compared to Windows) and more specifically why do I not get the same issue when using the Google server?

1 Answers

I wonder... is this as simple as a line-ending delta? Windows and Linux have different Environment.NewLine values. Perhaps try adding \r\n explicitly (since Windows seems to work), rather than relying on the local OS line-ending?

clearTextWriter.Write("HELO domain.com\r\n");

Also: try adding an explicit flush - clearTextWriter.Flush();.

As for why the Google server works: perhaps it is more forgiving in what it accepts, where-as the first server is following a specification more precisely, and that specification presumably says that messages are terminated by \r\n. Or the specification may be ambiguous, and Google just chose to be permissive.

BTW: for similar reasons, it would be a good idea to explicitly specify an Encoding here, presumably UTF8.

Related