YOUR FEEDBACK
Adobe Flex 2 - Answering Tough Questions About Enterprise Development
A Correct Person wrote: Denis Roebrt commented on the 21 Aug 2006 "Tough Que...

SYS-CON.TV
TOP MICROSOFT .NET LINKS


How To Implement Secure TCP Communications in Microsoft .NET 2.0
Microsoft .NET Framework 2.0 promises to be the first major upgrade to Windows and Web development tools

Digg This!

Page 2 of 2   « previous page

Listing 1: A simple TCP client application based on Microsoft sample code.

[C#]
//This code is modified Microsoft .NET Framework SDK Code

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

namespace ConsoleTcpClient
{
    
    class Client
    {
        
        [STAThread]
        static void Main(string[] args)
        {
            string server = “localhost”;
            string message = “This is a test”;
            int port = 13000;
            NetworkStream stream = null;
            try
            {
                // Step 1.
                // Instantiate a TcpClient with the target server 

and port number
                TcpClient client = new TcpClient(server, port);

                // Step 2.
                // Convert the data to send into a byte array
                Byte[] data = System.Text.Encoding.ASCII.GetBytes

(message);
                
// Step 3.
                // Get the NetworkStream for the TcpClient for 

sending and receiving
                stream = client.GetStream();

               
                // Step 4.
                // Send the message to the server. 
                stream.Write(data, 0, data.Length);

                //Write out the what was sent to the console
                Console.WriteLine(“Sent: {0}”, message);

               
                // Buffer to hold data returned from the server.
                data = new Byte[256];

                // String to store the response ASCII representation.
                //String responseData = String.Empty;
                // Step 5.
                // Read the response from the server up to the size 

of the buffer.
                int bytes = stream.Read(data, 0, data.Length);
                
                // Step 6.
                //Convert the received bytes into a string
                string responseData = System.Text.Encoding.ASCII.

GetString (data, 0, bytes);
                
                // Write out what was received to the console - 

this should be an “echo” of what // was sent.
                Console.WriteLine(“Received: {0}”, responseData);
            }
            
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Step 7.
                // Make sure that the NetworkStream is closed.
                if (stream != null)
                    stream.Close();
            }

            Console.WriteLine(“\n Press Enter to continue...”);
            Console.Read();
        }

       
    }
}

[Visual Basic]
‘This code is modified Microsoft .NET Framework SDK Code

Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Net.Sockets
Module Client

    Sub Main()
        Dim server As String = “localhost”
        Dim message As String = “This is a test”
        Dim port As Integer = 13000
        Dim stream As NetworkStream = Nothing
        Try

            ‘ Step 1.
            ‘ Instantiate a TcpClient with the target server and 

port number
            Dim client As New TcpClient(server, port)

            ‘ Step 2.
            ‘ Convert the data to send into a byte array
            Dim data As Byte() = System.Text.Encoding.ASCII.

GetBytes(message)

            ‘ Step 3.
            ‘ Get the NetworkStream for the TcpClient for sending 

and receiving
            stream = client.GetStream()

            ‘ Step 4.
            ‘ Send the message to the server. 
            stream.Write(Data, 0, Data.Length)

            ‘ Write out the what was sent to the console
            Console.WriteLine(“Sent: {0}”, message)

            ‘ Buffer to hold data returned from the server.
            data = New [Byte](256) {}

            ‘ String to store the response ASCII representation.
            ‘String responseData = String.Empty

            ‘ Step 5.
            ‘ Read the response from the server up to the size of 

the buffer.
            Dim bytes As Integer = stream.Read(data, 0, data.Length)

            ‘ Step 6.
            ‘ Convert the received bytes into a string
            Dim responseData As String = System.Text.Encoding.

ASCII.GetString (data, 0, bytes)

            ‘ Write out what was received to the console -

this should be an “echo” of what was sent.
            Console.WriteLine(“Received: {0}”, responseData)

        Catch ex As SocketException

            Console.WriteLine(ex.Message)

        Catch ex As IOException

            Console.WriteLine(ex.Message)

        Finally

            ‘ Step 7.
            ‘ Make sure that the NetworkStream is closed.
            If stream IsNot Nothing Then
                stream.Close()
            End If

            Console.WriteLine(“Press Enter to continue...”)
            Console.Read()
        End Try
    End Sub

End Module

Listing 2: A simple TCP listener application based on Microsoft example code.
[C#]
//This code is modified Microsoft .NET Framework SDK Code
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

namespace ConsoleTcpServer
{

    class Server
    {
        
        [STAThread]
        static void Main()
        {
            NetworkStream stream = null;
            try
            {
                
                int port = 13000;
                IPAddress localAddr = IPAddress.Loopback;

                // Step 1.
                // Instantiate an instance of the TcpListener
                TcpListener server = new TcpListener

(localAddr, port);

                // Step 2.
                // Start listening for incoming connections.
                server.Start();

                // Buffer to hold data received from the client.
                Byte[] bytes = new Byte[256];
                
                String data = null;

                // Step 3.
                // Loop while waiting for a connection.
                while (true)
                {
                    Console.Write("Waiting for a TcpClient 

connection... ");

                    // Step 4.
                    // Accept connection request in a blocking 

manner(the AcceptTcpClient method // is

blocking).
                    TcpClient client = server.AcceptTcpClient();
                    
                    Console.WriteLine("Connected!");

                    data = null;

                    // Step 5.
                    // Get a stream object for reading and writing
                    stream = client.GetStream();

                   
                    int i;

                    // Step 6.
                    // Loop to receive all the data sent by the 

client.
                    while ((i = stream.Read(bytes, 0, 

bytes.Length)) != 0)
                    {
                        // Convert the received bytes into a string.
                        data = System.Text.Encoding.ASCII.GetString

(bytes, 0, i);
                        
                        // Write the received data to the console.
                        Console.WriteLine("Received: {0}", data);

                        // Convert the string to upper case.
                        data = data.ToUpper(System.Globalization.

CultureInfo.CurrentCulture);

                        // Convert the data back into a byte array.
                        byte[] msg = System.Text.Encoding.ASCII.

GetBytes(data);

                        // Step 7.
                        // Send back the data that was received, 

but in upper case.
                        stream.Write(msg, 0, msg.Length);
                        
                        // Write the sent data to the console.
                        Console.WriteLine("Sent: {0}", data);
                    }
                }
            }
            
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Step 8.
                // Make sure the NetworkStream is closed.
                if (stream != null)
                    stream.Close();
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
    }
}

[Visual Basic]
'This code is modified Microsoft .NET Framework SDK Code
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Net.Sockets

Module Server

    Sub Main()
        Dim stream As NetworkStream = Nothing
        Try

            Dim port As Integer = 13000
            Dim localAddr As IPAddress = IPAddress.Loopback

            ' Step 1.
            ' Instantiate an instance of the TcpListener
            Dim Server As New TcpListener(localAddr, port)

            ' Step 2.
            ' Start listening for incoming connections.
            Server.Start()

            ' Buffer to hold data received from the client.
            Dim bytes(256) As Byte

            Dim data As String = Nothing

            ' Step 3.
            ' Loop while waiting for a connection.
            While (True)

                Console.Write("Waiting for a TcpClient

connection... ")

                ' Step 4.
                ' Accept connection request in a blocking manner 

(the AcceptTcpClient method is blocking).
                Dim client As TcpClient = Server.AcceptTcpClient()

                Console.WriteLine("Connected!")

                data = Nothing

                ' Step 5.
                ' Get a stream object for reading and writing
                Stream = client.GetStream()

                Dim i As Integer

                ' Step 6.
                ' Loop to receive all the data sent by the client.
                i = stream.Read(bytes, 0, bytes.Length)
                While (i <> 0)

                    ' Convert the received bytes into a string.
                    data = System.Text.Encoding.ASCII.GetString

(bytes, 0, i)

                    ' Write the received data to the console.
                    Console.WriteLine("Received: {0}", data)

                    ' Convert the string to upper case.
                    data = data.ToUpper(System.Globalization.

CultureInfo.CurrentCulture)

                    ' Convert the data back into a byte array.
                    Dim msg() As Byte = System.Text.Encoding.

ASCII.GetBytes(data)

                    ' Step 7.
                    ' Send back the data that was received, but 

in upper case.
                    stream.Write(msg, 0, msg.Length)

                    ' Write the sent data to the console.
                    Console.WriteLine("Sent: {0}", data)

                    i = stream.Read(bytes, 0, bytes.Length)
                End While
            End While

        Catch ex As SocketException

            Console.WriteLine(ex.Message)

        Catch ex As IOException

            Console.WriteLine(ex.Message)

        Finally

            ' Step 8.
            ' Make sure the NetworkStream is closed.
            If stream IsNot Nothing Then
                stream.Close()
            End If

            Console.WriteLine("Hit enter to continue...")
            Console.Read()
        End Try
    End Sub

End Module

Listing 3: A secure TCP client application that uses SslStream to encrypt the
transmission and authenticate the server.

[C#]
//This code is modified Microsoft .NET Framework SDK Code

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace ConsoleSecureTcpClient
{
    
    class SecureClient
    {
        
        [STAThread]
        static void Main()
        {
            string server = "localhost";
            string message = "This is a test";
            int port = 13000;
            SslStream stream = null;
            
            try
            {
                // Step 1.
                // Instantiate a TcpClient with the target server 

and port number
                TcpClient client = new TcpClient(server, port);

                // Step 2.
                // Convert the data to send into a byte array
                Byte[] data = System.Text.Encoding.ASCII.GetBytes

(message);

                // Step 3.
                // Specify the callback function that will act as the 

validation delegate. This // lets you

inspect the certificate to see if

it meets your

// validation requirements.
                RemoteCertificateValidationCallback callback = new
RemoteCertificateValidationCallback(OnCertificateValidation);
                
                // Step 4.
                // Instantiate an SslStream with the NetworkStream 

returned from the TcpClient.
                stream = new SslStream(client.GetStream(), false, 

callback);

                // Step 5.
                // As a client, you can authenticate the server 

and validate the results using the

// SslStream.
                // This is the host name of the server you are 

connecting to, which may or may not // be

the name used to connect to the

server when TcpClient is instantiated.
                stream.AuthenticateAsClient(server);
                if (stream.IsAuthenticated)
                {
                    // Indicates whether the authentication was 

successful.
                    Console.WriteLine("IsAuthenticated: {0}", 

stream.IsAuthenticated);
                    // Indicates whether both the client and server 

has been authenticated.
                    // In this example only the server is 

authenticated.
                    Console.WriteLine("IsMutuallyAuthenticated: 

{0}", stream.IsMutuallyAuthenticated);
                    // Indicates whether the SslStream uses data 

encryption.
                    Console.WriteLine("IsEncrypted: {0}", stream.

IsEncrypted);
                    // Indicates whether the data sent is signed.
                    Console.WriteLine("IsSigned: {0}", stream.

IsSigned);
                    // Indicates whether the current side of the 

connection is authenticated as a // server.
                    Console.WriteLine("IsServer: {0}", stream.
IsServer);
                }

                // Step 6.
                // Send the message to the server. 
                stream.Write(data, 0, data.Length);

                // Write out the what was sent to the console
                Console.WriteLine("Sent: {0}", message);

               
                // Buffer to hold data returned from the server.
                data = new Byte[256];

                // Step 7.
                // Read the response from the server up to the 

size of the buffer.
                int bytes = stream.Read(data, 0, data.Length);
                
                // Step 8.
                // Convert the received bytes into a string
                string responseData = System.Text.Encoding.ASCII.

GetString (data, 0, bytes);
                
                // Write out what was received to the console - 

this should be an "echo" of what // was sent.
                Console.WriteLine("Received: {0}", responseData);
            }
            catch (AuthenticationException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Step 9.
                // Make sure that the SslStream is closed.
                if (stream != null)
                    stream.Close();
            }

            Console.WriteLine("\n Press Enter to continue...");
            Console.Read();
        }
        // Check the certificate for errors and to make sure it meets 

your security policy.
        private static bool OnCertificateValidation(object sender, 

X509Certificate certificate, X509Chain chain,

SslPolicyErrors errors)
        {
            Console.WriteLine("Server Certificate Issued To: {0}", 

certificate.GetName());
            Console.WriteLine("Server Certificate Issued By: {0}", 

certificate.GetIssuerName());

            // Return true if there are no policy errors
            // The certificate can also be manually verified to 

make sure it meets your specific // policies by

interrogating the x509Certificate object.
            if (errors != SslPolicyErrors.None)
            {
                Console.WriteLine("Server Certificate Validation 

Error");
                Console.WriteLine(errors.ToString());
                return false;
            }
            else
            {
                Console.WriteLine("No Certificate Validation Errors");
                return true;
            }
        }

    }
}

[Visual Basic]
'This code is modified Microsoft .NET Framework SDK Code

Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Net.Sockets
Imports System.Net.Security
Imports System.Security.Authentication
Imports System.Security.Cryptography.X509Certificates
Module SecureClient

    Sub Main()
        Dim server As String = "localhost"
        Dim message As String = "This is a test"
        Dim port As Integer = 13000
        Dim Stream As SslStream = Nothing

        Try

            ' Step 1.
            ' Instantiate a TcpClient with the target server and 

port number
            Dim client As New TcpClient(server, port)

            ' Step 2.
            'Convert the data to send into a byte array
            Dim data As [Byte]() = System.Text.Encoding.ASCII.

GetBytes(message)

            ' Step 3.
            ' Specify the callback function that will act as the 

validation delegate. This lets you inspect '

the certificate to see if it meets your '

validation requirements.
            Dim callback As New RemoteCertificateValidationCallback

(AddressOfOnCertificateValidation)

            ' Step 4.
            ' Instantiate an SslStream with the NetworkStream 

returned from the TcpClient.
            Stream = New SslStream(client.GetStream(), False, callback)

            ' Step 5.
            ' As a client, you can authenticate the server and 

validate the results using the SslStream.
            ' This is the host name of the server you are connecting 

to, which may or may not be the name ' used
            ' to connect to the server when TcpClient is instantiated.
            Stream.AuthenticateAsClient(server)
            If Stream.IsAuthenticated Then

                ' Indicates whether the authentication was successful.
                Console.WriteLine("IsAuthenticated: {0}", Stream.

IsAuthenticated)
                ' Indicates whether both the client and server has 

been authenticated.
                ' In this example only the server is authenticated.
                Console.WriteLine("IsMutuallyAuthenticated: {0}", 

Stream.IsMutuallyAuthenticated)
                ' Indicates whether the SslStream uses data encryption.
                Console.WriteLine("IsEncrypted: {0}", Stream.Is

Encrypted)
                ' Indicates whether the data sent is signed.
                Console.WriteLine("IsSigned: {0}", Stream.IsSigned)
                ' Indicates whether the current side of the connection is 

authenticated as a server.
                Console.WriteLine("IsServer: {0}", Stream.IsServer)
            End If

            ' Step 6.
            ' Send the message to the server. 
            Stream.Write(data, 0, data.Length)

            ' Write out the what was sent to the console
            Console.WriteLine("Sent: {0}", message)

            ' Buffer to hold data returned from the server.
            data = New [Byte](256) {}

            ' Step 7.
            ' Read the response from the server up to the size of the buffer.
            Dim bytes As Integer = Stream.Read(data, 0, data.Length)

            ' Step 8.
            ' Convert the received bytes into a string
            Dim responseData As String = System.Text.Encoding.ASCII.

GetString(data, 0, bytes)

            ' Write out what was received to the console - this should

be an "echo" of what was sent.
            Console.WriteLine("Received: {0}", responseData)

        Catch ex As AuthenticationException

            Console.WriteLine(ex.Message)

        Catch ex As SocketException

            Console.WriteLine(ex.Message)

        Catch ex As IOException

            Console.WriteLine(ex.Message)

        Finally

            ' Step 9.
            ' Make sure that the SslStream is closed.
            If Stream IsNot Nothing Then
                Stream.Close()
            End If

            Console.WriteLine("Press Enter to continue...")
            Console.Read()
        End try
    End Sub
    'Check the certificate for errors and to make sure it meets your 

security policy.
    Private Function OnCertificateValidation(ByVal sender As Object,


Page 2 of 2   « previous page

About Alexander Gladshtein
Alex Gladshtein is a product manager at The CBORD Group, Inc. in Ithaca, NY. CBORD is the world's largest supplier of food and nutrition software solutions, campus-wide ID card programs, cashless dining, and housing management systems. Alex holds undergraduate and graduate degrees from the University of Michigan, and when not obsessing about .NET he enjoys spending time with his wonderful wife and cheering on the Michigan Wolverines.

orjan lindahl wrote: The listing is incomplete, part of listing 3 and all of listing 4 is missing
read & respond »
PatchTuesday wrote: Microsoft updates its Malicious Software Removal Tool tomorrow - plus a welter of security patches.
read & respond »
.NET News Desk wrote: How To Implement Secure TCP Communications in Microsoft .NET 2.0 The release of the .NET Framework 2.0 promises to be the first major upgrade to Windows and Web development tools since the initial release of .NET in 2001. In the realm of general networking, some of the major improvements to the Framework include FTP, Ping, packet tracing, and revised SMTP/MIME classes that are not dependent on the Windows SMTP service.
read & respond »
.NET News Desk wrote: How To Implement Secure TCP Communications in Microsoft .NET 2.0 The release of the .NET Framework 2.0 promises to be the first major upgrade to Windows and Web development tools since the initial release of .NET in 2001. In the realm of general networking, some of the major improvements to the Framework include FTP, Ping, packet tracing, and revised SMTP/MIME classes that are not dependent on the Windows SMTP service.
read & respond »
MICROSOFT .NET LATEST STORIES
Icahn Moves To Force Microsoft & Yahoo Together
Corporate raider Carl Icahn started his proxy fight for control of Yahoo this morning, beginning with the classic Icahn opening, the letter of reproach to the Yahoo board telling them they have acted 'irrationally and lost the faith of shareholders and Microsoft.'
IBM, Microsoft & Google Eras of Computing
By now it is conventional wisdom to say that there was an IBM Era of computing, then a Microsoft Era, and now we are in the Google Era. In this post, I will explain why Microsoft was not the 'next IBM' and why Google is not the 'next Microsoft' - there are significant qualitative diffe
Book Review: ASP.NET 2.0
ASP.NET developers are bored with traditional books that outline concepts in a lengthy way. These books are good if you like to learn the features in a detailed manner. However, by the time the book is read, a new version will be released. Hence, many learners including myself prefer s
3rd International Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
"RIA" vs "Rich Client Platform": The Term Is Now Up for Debate
'RIA' is slowly fading in terms of its definition. When I first started the RIA Evangelism role in Microsoft, I had this nagging feeling that the term RIA was just all over the place. Depending on which technology you are backing and which stream of alliance you uphold, the truth is th
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING NEWS FROM THE WIRES
Strangeloop Networks Selected for Red Herring 100 North America 2008
Strangeloop Networks (TM) Inc., a leading provider of solutions that accelerate dynamic web