Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#
Article

Implement a basic IP Scanner for a local LAN in C#

Rate me:
Please Sign up or sign in to vote.
3.38/5 (15 votes)
23 Apr 2005 151.6K   8.4K   51   18
Shows how to make a basic IP Scanner.

Sample Image - C__IP_Scanner.jpg

Introduction

This is a very basic IP Scanner written in C#. I searched a long time and couldn't find something done in C# similar to what I wrote. So I decided to put it on the Code Project.

Ok.. now how to implement it ?

For those of you who have written a TCP/IP program it's more than easy... Basically after getting the From .. To IPAddresses, all you do is, call  Dns.GetHostByAddress.

Here is the most important part of the App:

C#
try
{
    
  string address = ipTo.Text.Substring(0,lastT+1);
  System.Diagnostics.Debug.WriteLine(ipTo.Text.Substring(0,lastT+1)+i);
  IPHostEntry he = Dns.GetHostByAddress( address+i);
  Add( he.HostName );
  result += 1;
}
catch( SocketException )
{
  // in cazul unei erori : Romanian for -> in case of an error
}
catch( Exception )
{
  // previne bloacarea programului
 
}// it prevents the App from crashing

Ok , that's it ... yes .. for the implementation, get the code Or copy/paste this >...

/*
* Author : Lazar Mihai
* 
* It shows how to do simple scan of the network inside a local LAN.
* 
* The program is straith forward for any questions, comments or sugestions
* please write me an e -mail at : sharpoverride@gmail.com 
* 
* */
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace GetStations
{
  /// <summary>
  /// Summary description for Form1.
  /// </summary>
  public class Form1 : System.Windows.Forms.Form
  { 
    private System.Windows.Forms.Label label1;

    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.TextBox ipFrom;
    private System.Windows.Forms.TextBox ipTo;
    private System.Windows.Forms.TextBox hostName;
    private System.Windows.Forms.Button btnUse;
    private System.Windows.Forms.ListBox add;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Button btnStart;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

    public Form1()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
      LoadMe();
    }
    void LoadMe()
    {
      hostName.Text = Dns.GetHostName();
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.label1 = new System.Windows.Forms.Label();
      this.label2 = new System.Windows.Forms.Label();
      this.ipFrom = new System.Windows.Forms.TextBox();
      this.ipTo = new System.Windows.Forms.TextBox();
      this.hostName = new System.Windows.Forms.TextBox();
      this.btnUse = new System.Windows.Forms.Button();
      this.add = new System.Windows.Forms.ListBox();
      this.label3 = new System.Windows.Forms.Label();
      this.btnStart = new System.Windows.Forms.Button();
      this.SuspendLayout();
      // 
      // label1
      // 
      this.label1.Location = new System.Drawing.Point(32, 32);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(88, 24);
      this.label1.TabIndex = 0;
      this.label1.Text = "Ip Range:";
      this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      // 
      // label2
      // 
      this.label2.Location = new System.Drawing.Point(32, 64);
      this.label2.Name = "label2";
      this.label2.Size = new System.Drawing.Size(88, 24);
      this.label2.TabIndex = 1;
      this.label2.Text = "Host :";
      this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      // 
      // ipFrom
      // 
      this.ipFrom.Location = new System.Drawing.Point(128, 32);
      this.ipFrom.Name = "ipFrom";
      this.ipFrom.Size = new System.Drawing.Size(160, 20);
      this.ipFrom.TabIndex = 2;
      this.ipFrom.Text = "127.0.0.1";
      // 
      // ipTo
      // 
      this.ipTo.Location = new System.Drawing.Point(328, 32);
      this.ipTo.Name = "ipTo";
      this.ipTo.Size = new System.Drawing.Size(160, 20);
      this.ipTo.TabIndex = 3;
      this.ipTo.Text = "127.0.0.1";
      // 
      // hostName
      // 
      this.hostName.Location = new System.Drawing.Point(128, 64);
      this.hostName.Name = "hostName";
      this.hostName.Size = new System.Drawing.Size(128, 20);
      this.hostName.TabIndex = 4;
      this.hostName.Text = "";
      // 
      // btnUse
      // 
      this.btnUse.Location = new System.Drawing.Point(280, 64);
      this.btnUse.Name = "btnUse";
      this.btnUse.Size = new System.Drawing.Size(40, 24);
      this.btnUse.TabIndex = 5;
      this.btnUse.Text = "Use";
      this.btnUse.Click += new System.EventHandler(this.UseClick);
      // 
      // add
      // 
      this.add.Location = new System.Drawing.Point(64, 120);
      this.add.Name = "add";
      this.add.Size = new System.Drawing.Size(552, 264);
      this.add.TabIndex = 6;
      // 
      // label3
      // 
      this.label3.Location = new System.Drawing.Point(296, 32);
      this.label3.Name = "label3";
      this.label3.Size = new System.Drawing.Size(24, 24);
      this.label3.TabIndex = 7;
      this.label3.Text = "to";
      this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      // 
      // btnStart
      // 
      this.btnStart.Location = new System.Drawing.Point(432, 64);
      this.btnStart.Name = "btnStart";
      this.btnStart.Size = new System.Drawing.Size(112, 40);
      this.btnStart.TabIndex = 8;
      this.btnStart.Text = "Start !";
      this.btnStart.Click += new System.EventHandler(this.StartClick);
      // 
      // Form1
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(680, 422);
      this.Controls.Add(this.btnStart);
      this.Controls.Add(this.label3);
      this.Controls.Add(this.add);
      this.Controls.Add(this.btnUse);
      this.Controls.Add(this.hostName);
      this.Controls.Add(this.ipTo);
      this.Controls.Add(this.ipFrom);
      this.Controls.Add(this.label2);
      this.Controls.Add(this.label1);
      this.Name = "Form1";
      this.Text = "Find network";
      this.ResumeLayout(false);

    }
    #endregion

    void Add( string m )
    {
      add.Items.Add( m );
    }
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new Form1());
    }

    private void UseClick(object sender, System.EventArgs e)
    {
      //When pressing the use use button
    
      IPHostEntry ip = Dns.GetHostByName( Dns.GetHostName() );
      ipFrom.Text = ip.AddressList[0].ToString();
      ipTo.Text = ip.AddressList[0].ToString();


    }
    Thread sercher ;
 
    private void StartClick(object sender, System.EventArgs e)
    {
      sercher = new Thread( new ThreadStart( Find ));
      add.Items.Clear();
      try
      {
        IPAddress from = IPAddress.Parse( ipFrom.Text );
        IPAddress to = IPAddress.Parse( ipTo.Text );
      }
      catch( FormatException fe )
      {
        MessageBox.Show( fe.Message );
        return;
      }
      sercher.Name = "Network searching thread";
      sercher.Start();
      add.Items.Add( "-->> >>> Please wait while processing is done <<< <<--" );
      Thread.Sleep(1);// pune la culcare Threadul principal

    }
    /// <summary>
    /// 
    /// </summary>
    void Find( ) // 
    {
      Add( "-- >>> >> >>> Found station <<< << <<< -- " );
      int lastF = ipFrom.Text.LastIndexOf(".");
      int lastT = ipTo.Text.LastIndexOf(".");
      string frm = ipFrom.Text.Substring(lastF+1);
      string tto = ipTo.Text.Substring(lastT+1);
      int result = 0;
      System.Diagnostics.Debug.WriteLine( frm + " " + tto);
      for( int i = int.Parse( frm); i <= int.Parse(tto );i++)
      {
        try
        {
          string address = ipTo.Text.Substring(0,lastT+1);
          System.Diagnostics.Debug.WriteLine(ipTo.Text.Substring(0,lastT+1)+i);
          IPHostEntry he = Dns.GetHostByAddress( address+i);
          Add( he.HostName );
          result += 1;
        }

        catch( SocketException )
        {
          // in cazul unei erori
        }
        catch( Exception )
        {
          // previne bloacarea programului
        }
      }

    }
  }

}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Junior)
Romania Romania
I'm an average programmer, that hopes to be of some help to others.

Moto
------------------------------------------------------
The road to becoming a good programmer is paved with bad scripts.

Comments and Discussions

 
Suggestionfix for threading issue Pin
RandomFool29-Jul-21 9:48
RandomFool29-Jul-21 9:48 
Bugnot listing stations Pin
costavo5-Nov-13 20:00
costavo5-Nov-13 20:00 
GeneralMy vote of 4 Pin
Burak Tunçbilek7-Jan-13 8:02
Burak Tunçbilek7-Jan-13 8:02 
GeneralMy vote of 4 Pin
asdf900913-Aug-12 22:50
asdf900913-Aug-12 22:50 
Questionthanks for code which was for my exam project Pin
Ferit MİRBEY24-Dec-11 12:11
Ferit MİRBEY24-Dec-11 12:11 
GeneralThanks. Pin
txghia586-Feb-09 10:41
txghia586-Feb-09 10:41 
Questionerror Visual Studio 2005 Pin
Devil66667-May-07 11:55
Devil66667-May-07 11:55 
AnswerRe: error Visual Studio 2005 Pin
Sharpoverride8-May-07 9:28
Sharpoverride8-May-07 9:28 
QuestionRe: error Visual Studio 2005 Pin
Devil66669-May-07 5:55
Devil66669-May-07 5:55 
QuestionIs there a way to detect Network Printers' IP addresses? Pin
Jan Palmer25-Dec-06 20:42
Jan Palmer25-Dec-06 20:42 
Generalnot thread safe.... Pin
Timur Zanagar18-Feb-06 10:08
Timur Zanagar18-Feb-06 10:08 
GeneralRe: not thread safe.... Pin
Devil66667-May-07 11:34
Devil66667-May-07 11:34 
GeneralRe: not thread safe.... Pin
Didjeeh4-Nov-07 22:34
Didjeeh4-Nov-07 22:34 
GeneralRe: not thread safe.... Pin
Yusuf7ate620-Jun-08 11:08
Yusuf7ate620-Jun-08 11:08 
GeneralRe: not thread safe.... Pin
Ferit MİRBEY24-Dec-11 12:08
Ferit MİRBEY24-Dec-11 12:08 
thanks for thread-safe method Smile | :)
QuestionScanning in internet? Pin
niting8023-Dec-05 8:06
niting8023-Dec-05 8:06 
GeneralYour french suck Pin
Kevin Alexandre24-Apr-05 5:50
Kevin Alexandre24-Apr-05 5:50 
GeneralRe: Your french suck Pin
mark_md415-Dec-06 21:21
mark_md415-Dec-06 21:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.