News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Telnet a remote service using C#


Sometimes your application connects to remote services for any purpose such as querying a database, sending e-mails, sending SMS and etc. You need to make sure that the service is running and accept incoming connections across the network. One simple method is to telnet it using the command line by writing the following command line:

Telnet [Server IP Address] [Service Port Number]

But if you want to make sure that the service is running from your application! Let us show what the telnet command does? It tries to establish a TCP/IP connection to the server on a specific port number. The good news is that the System.Net.Sockets has the Socket class that provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration. In this article we will see how to use the Socket class to check that a service is running on a remote server.

Using the Code:

To make your application make sure a server is reachable across the network, follow these steps:

1.       Create a new windows application using Visual Studio 2005/2008.

2.       Rename Form1 to TelnetForm.

3.       Add a TextBox to the TelnetForm and rename it to IPTextBox.

4.       Add another TextBox to the TelnetForm and rename it to PortTextBox.

5.       Import the System.Net and System.Net.Sockets namespaces using the following statement:

using System.Net;

using System.Net.Sockets;

6.       The System.Net namespace provides a simple programming interface for many of the protocols used on networks today.

7.       The System.Net.Sockets namespace provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to tightly control access to the network.

8.        Add a button to the TelnetForm and name it TelnetButton and double click the TelnetButton in the designer to create the Click event handler in the code.

9.       Add the following code to the TelnetButton Click Event Handler:

private Socket clientSocket;

private IPAddress hostAddress;

private void TelnetButton_Click(object sender, EventArgs e)

{

    try

    {

        if (string.IsNullOrEmpty(IPTextBox.Text))

            return;

 

        if (string.IsNullOrEmpty(PortTextBox.Text))

            return;

 

        int port;

        hostAddress = Dns.GetHostEntry(IPTextBox.Text).AddressList[0];

        int.TryParse(PortTextBox.Text, out port);

 

        if (hostAddress.AddressFamily == AddressFamily.InterNetwork)

            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)

            clientSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

 

        SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();

        telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(hostAddress, port);

        telnetSocketAsyncEventArgs.Completed += new

            EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);

 

        clientSocket.ConnectAsync(telnetSocketAsyncEventArgs);

    }

    catch (SocketException ex)

    {

        MessageBox.Show(ex.Message, "Service Is not Running",

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    finally

    {

    }

}

a.       In the above code we check that the IPtextBox and PortTextBox have values.

b.      Create an instance of IPAddress and name it hostAddress. This class provides an Internet Protocol (IP) address and the IPAddress class contains the address of a computer on an IP network.

c.       We use the Dns class that provides simple domain name resolution functionality to get the IP address if the user types the server name by using the GetHosEntry method that resolves a host name or IP address to an IPHostEntry instance.

d.      We check the IPAddress instance address family to create a socket with this address family. AddressFamily specifies the addressing scheme that a Socket will use to resolve an address.

e.      We then create a new instance of the Socket class and name it clientSocket and initialize it with the address family of the hostAddress, socket type and protocol type that we use in this article we use the TCP protocol.

f.        We then create an instance of the SocketAsyncEventArgs Class and name it telnetSocketAsyncEventArgs. The SocketAsyncEventArgs class represents an asynchronous socket operation. The SocketAsyncEventArgs class is part of a set of enhancements to the System.Net.Sockets.Socket class that provide an alternative asynchronous pattern that can be used by specialized high-performance socket applications.

g.       Set the telnetSocketAsyncEventArgs object RemoteEndPoint property with a new instance of the IPEndPoint class and pass it the hostAddress and port number that we need to connect to.

h.      We implement the Completed event of the telnetSocketAsyncEventArgs object. This event is used to complete an asynchronous operation.

i.         We then call the clientSocket ConnectAsync method and pass it the telnetSocketAsyncEventArgs that will fire the completed event when the connection success or fails.

10.   After that we should add the code that tell us that the connection is succeeded or failed by adding the following code in the telnetSocketAsyncEventArgs_Completed method created in the previous step.

private void telnetSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)

{

    try

    {

        if (e.SocketError == SocketError.Success)

        {

            if (e.LastOperation == SocketAsyncOperation.Connect)

            {

                MessageBox.Show("Service Is Running", hostAddress.ToString(),

                    MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }

        else

        {

            MessageBox.Show("Service Is not Running", e.SocketError.ToString(),

                MessageBoxButtons.OK, MessageBoxIcon.Error);

        }

    }

    catch (SocketException ex)

    {

        MessageBox.Show(ex.Message, "Service Is not Running",

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

a.       In the above code we check that the connection is succeeded and there is no errors returned from the asynchronous socket operation.

b.      We then check that the last operation is Connect operation and tell the user that the service is running.

c.       If there are errors we tell the user that the service is not running and state the socket error returned.

11.   Now compile and run the application.

12.   Enter any IP address or Name of the computer and the port number of that the service is listening on and click on the TelnetButton.

13.   You will be notified if the remote service is running or not.


Now you have an application that can telnet a remote service and tells you if the service is running or not.

(474) Comments

Blog Message Rahul

how can we pass command and read the respnose.


Blog Message Rahul

how can we pass command and read the respnose.


Blog Message https://www.evernote.com/shard/s667/sh/e2967c12-63da-4f9a-a98e-ae6b8002fef0/bf963b444d4357319c9dd55365ad418c

It is laborious to search out knowledgeable people on this matter, but you sound like you recognize what you are speaking about! Thanks


Blog Message http://www.infomapp.com/p/kitesurfing-mui-ne-price/

I really enjoy the post.Really thank you! Cool.


Blog Message http://tiger77.net/daftar-situs-bola-piala-dunia-2018-terpercaya/

Thanks for sharing, this is a fantastic article post.Really looking forward to read more. Really Cool.


Blog Message http://ma7sobak.net/user/profile/177023

I?ll right away clutch your rss as I can at to find your e-mail subscription link or newsletter service. Do you ave any? Please allow me know in order that I may subscribe. Thanks.


Blog Message http://sol.1c.ru/bitrix/redirect.php?event1=&event2=&event3=&goto=http://www.directory4india.com/story.php?title=agario-games

This is my first time go to see at here and i am in fact impressed to read everthing at single place.


Blog Message https://www.instapaper.com/read/1009124795

I loved your blog post. Great.


Blog Message http://weed4allpurpose.com

Really enjoyed this post.Thanks Again. Want more.


Blog Message https://www.youtube.com/watch?v=KKOyneFvYs8

Really appreciate you sharing this blog.Thanks Again. Fantastic.


Blog Message http://airsoftforum.at/index.php?PHPSESSID=9a1a0b5c453537bcbc305e2492fe766c&action=profile;area=showThankYouPosts;sa=messages_given;u=144&pid=961

Wow, great article post.Really thank you! Will read on


Blog Message http://menstrength-hub.online/story/10587

This is really interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your wonderful post. Also, I ave shared your web site in my social networks!


Blog Message http://www.bookcentral.in/user/profile/221836

I really love your site.. Very nice colors & theme. Did you make this site yourself? Please reply back


Blog Message https://www.amazon.com/Antibacterial-Silicone-Poschtek-Resistant-Countertop/dp/B077H46P22

Im obliged for the post.Much thanks again. Much obliged.


Blog Message http://footbolt28.webgarden.at/kategorien/footbolt28-s-blog/unrivaled-gardening-services

This excellent website truly has all of the information and facts I wanted about this subject and didn at know who to ask.

First Previous 1 2 3 4 5 6 7 8 9 10  ... Next Last 
Rating
Name
Email
Comment