Retrieve (Get) IP Address from database and check status is online or offline using C# and VB.Net in ASP.Net

indradeo
 
on Nov 24, 2021 03:11 AM
Sample_142395.zip
858 Views

i have one table where i have saved ip_address details. i want to check all ip_address details. if ip online then status display "ON" if ip offline then status display "OFF"

CREATE TABLE [dbo].[emp_ip] (
    [Id]      INT         NOT NULL,
    [emp_id]  NCHAR (10)  NULL,
    [emp_nm]  NCHAR (50)  NULL,
    [ip_add]  NVARCHAR(MAX)  NULL,
    [mc_add]  NCHAR (100) NULL,
    [mchnInm] NCHAR (100) NULL,
    [dt]      NCHAR (10)  NULL,
    [stts]    NCHAR (10)  NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

 

namespace Network_auto_ping
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable pingResults = new DataTable();
            pingResults.Columns.AddRange(new DataColumn[] {
                    new DataColumn("Date", typeof(DateTime)),
                    new DataColumn("IP", typeof(string)),
                    new DataColumn("MacAddress",typeof(string)),
                    new DataColumn("MachineName",typeof(string)),
                    new DataColumn("Message",typeof(string)),
                    new DataColumn("Emp_Name",typeof(string))});
            try
            {
                pingResults.Clear();

                List<string> ipAddress = new List<string>();
                ipAddress.Add("10.1.246.41");
                ipAddress.Add("10.1.246.59");
                ipAddress.Add("10.1.246.14");
                ipAddress.Add("10.1.150.11");
                ipAddress.Add("10.1.246.233");
                ipAddress.Add("10.1.246.62");
                ipAddress.Add("10.1.246.4");
                ipAddress.Add("10.1.246.8");
                ipAddress.Add("10.1.250.11");
                ipAddress.Add("192.168.200.181");


                List<string> Emp_Name = new List<string>();
                Emp_Name.Add("MTTP Intranet");
                Emp_Name.Add("Indradeo PC");
                Emp_Name.Add("Anurakshan PC");
                Emp_Name.Add("NAS PC");
                Emp_Name.Add("NOT IN NETWORK");
                Emp_Name.Add("Amrita PC");
                Emp_Name.Add("MTTP Intranet BACK-UP PC");
                Emp_Name.Add("PIMEJA PC");
                Emp_Name.Add("MAHADEV PC");
                Emp_Name.Add("Engineer(IT)");

                for (int i = 0; i < ipAddress.Count; i++)
                {
                    Ping ping = new Ping();
                    PingReply pingReply = ping.Send(ipAddress[i].ToString());
                    string message = (pingReply.Status == IPStatus.Success) ? "On" : "Off";
                    lock (pingResults.Rows.SyncRoot)
                    {
                        pingResults.Rows.Add(DateTime.Now, ipAddress[i], GetMacAddress(ipAddress[i]), GetMachineName(ipAddress[i]), message, Emp_Name[i]);
                    }
                    Thread.Sleep(1000);
                }
                GridView1.DataSource = pingResults;
                GridView1.DataBind();

            }
            catch (Exception ex)
            {

            }
        }

        public string GetMacAddress(string ipAddress)
        {
            string macAddress = string.Empty;
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = "arp";
            pProcess.StartInfo.Arguments = "-a " + ipAddress;
            pProcess.StartInfo.UseShellExecute = false;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow = true;
            pProcess.Start();
            string strOutput = pProcess.StandardOutput.ReadToEnd();
            string[] substrings = strOutput.Split('-');
            if (substrings.Length >= 8)
            {
                macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2))
                            + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6]
                            + "-" + substrings[7] + "-"
                            + substrings[8].Substring(0, 2);
                return macAddress;
            }
            else
            {
                return "not found";
            }
        }

        private string GetMachineName(string ipAdress)
        {
            string machineName = string.Empty;
            try
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(ipAdress);
                machineName = hostEntry.HostName;
            }
            catch (Exception ex)
            {

            }
            return machineName;
        }
        protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (!string.IsNullOrEmpty(e.Row.Cells[4].Text))
                {
                    if (e.Row.Cells[4].Text == "On")
                    {
                        e.Row.Cells[4].ForeColor = System.Drawing.Color.Black;
                        e.Row.Cells[4].BackColor = System.Drawing.Color.Green;
                    }
                    else
                    {
                        e.Row.Cells[4].ForeColor = System.Drawing.Color.Black;
                        e.Row.Cells[4].BackColor = System.Drawing.Color.Red;
                    }
                }
            }
        }
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunv
 
on Nov 24, 2021 04:52 AM
on Nov 25, 2021 02:03 AM

Hi Indradeo,

 Please refer below sample.

HTML

<asp:GridView runat="server" ID="GridView1" OnRowDataBound="OnRowDataBound" />

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading

VB.net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    DataTable pingResults = new DataTable();
    pingResults.Columns.AddRange(new DataColumn[] {
                new DataColumn("Date", typeof(DateTime)),
                new DataColumn("IP", typeof(string)),
                new DataColumn("MacAddress",typeof(string)),
                new DataColumn("MachineName",typeof(string)),
                new DataColumn("Message",typeof(string)),
                new DataColumn("Emp_Name",typeof(string))});
    try
    {
        pingResults.Clear();

        List<Employee> employees = GetDetails();
            
        for (int i = 0; i < employees.Count; i++)
        {
            Ping ping = new Ping();
            PingReply pingReply = ping.Send(employees[i].ipAddress);
            string message = (pingReply.Status == IPStatus.Success) ? "On" : "Off";
            lock (pingResults.Rows.SyncRoot)
            {
                pingResults.Rows.Add(DateTime.Now, employees[i].ipAddress, GetMacAddress(employees[i].ipAddress), GetMachineName(employees[i].ipAddress), message, employees[i].Emp_Name);
            }
            Thread.Sleep(1000);
        }
        GridView1.DataSource = pingResults;
        GridView1.DataBind();

    }
    catch (Exception ex)
    {

    }
}

public class Employee
{
    public string ipAddress { get; set; }
    public string Emp_Name { get; set; }
}


private List<Employee> GetDetails()
{
    List<Employee> employees = new List<Employee>();
    string cs = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT emp_nm,ip_add FROM emp_ip", con))
        {
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                employees.Add(new Employee
                {
                    Emp_Name = sdr["emp_nm"].ToString(),
                    ipAddress = sdr["ip_add"].ToString()
                });
            }
            con.Close();
        }
    }

    return employees;
}

public string GetMacAddress(string ipAddress)
{
    string macAddress = string.Empty;
    System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
    pProcess.StartInfo.FileName = "arp";
    pProcess.StartInfo.Arguments = "-a " + ipAddress;
    pProcess.StartInfo.UseShellExecute = false;
    pProcess.StartInfo.RedirectStandardOutput = true;
    pProcess.StartInfo.CreateNoWindow = true;
    pProcess.Start();
    string strOutput = pProcess.StandardOutput.ReadToEnd();
    string[] substrings = strOutput.Split('-');
    if (substrings.Length >= 8)
    {
        macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2))
                    + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6]
                    + "-" + substrings[7] + "-"
                    + substrings[8].Substring(0, 2);
        return macAddress;
    }
    else
    {
        return "not found";
    }
}

private string GetMachineName(string ipAdress)
{
    string machineName = string.Empty;
    try
    {
        IPHostEntry hostEntry = Dns.GetHostEntry(ipAdress);
        machineName = hostEntry.HostName;
    }
    catch (Exception ex)
    {

    }
    return machineName;
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (!string.IsNullOrEmpty(e.Row.Cells[4].Text))
        {
            if (e.Row.Cells[4].Text == "On")
            {
                e.Row.Cells[4].ForeColor = System.Drawing.Color.Black;
                e.Row.Cells[4].BackColor = System.Drawing.Color.Green;
            }
            else
            {
                e.Row.Cells[4].ForeColor = System.Drawing.Color.Black;
                e.Row.Cells[4].BackColor = System.Drawing.Color.Red;
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim pingResults As DataTable = New DataTable()
    pingResults.Columns.AddRange(New DataColumn() {New DataColumn("Date", GetType(DateTime)), New DataColumn("IP", GetType(String)), New DataColumn("MacAddress", GetType(String)), New DataColumn("MachineName", GetType(String)), New DataColumn("Message", GetType(String)), New DataColumn("Emp_Name", GetType(String))})
    Try
        pingResults.Clear()
        Dim employees As List(Of Employee) = GetDetails()
        For i As Integer = 0 To employees.Count - 1
            Dim ping As Ping = New Ping()
            Dim pingReply As PingReply = ping.Send(employees(i).ipAddress)
            Dim message As String = If((pingReply.Status = IPStatus.Success), "On", "Off")

            SyncLock pingResults.Rows.SyncRoot
                pingResults.Rows.Add(DateTime.Now, employees(i).ipAddress, GetMacAddress(employees(i).ipAddress), GetMachineName(employees(i).ipAddress), message, employees(i).Emp_Name)
            End SyncLock

            Thread.Sleep(1000)
        Next

        GridView1.DataSource = pingResults
        GridView1.DataBind()
    Catch ex As Exception
    End Try
End Sub

Public Class Employee
    Public Property ipAddress As String
    Public Property Emp_Name As String
End Class

Private Function GetDetails() As List(Of Employee)
    Dim employees As List(Of Employee) = New List(Of Employee)()
    Dim cs As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(cs)
        Using cmd As SqlCommand = New SqlCommand("SELECT emp_nm,ip_add FROM emp_ip", con)
            con.Open()
            Dim sdr As SqlDataReader = cmd.ExecuteReader()
            While sdr.Read()
                employees.Add(New Employee With {
                .Emp_Name = sdr("emp_nm").ToString(),
                .ipAddress = sdr("ip_add").ToString()
            })
            End While
            con.Close()
        End Using
    End Using

    Return employees
End Function

Public Function GetMacAddress(ByVal ipAddress As String) As String
    Dim macAddress As String = String.Empty
    Dim pProcess As System.Diagnostics.Process = New System.Diagnostics.Process()
    pProcess.StartInfo.FileName = "arp"
    pProcess.StartInfo.Arguments = "-a " & ipAddress
    pProcess.StartInfo.UseShellExecute = False
    pProcess.StartInfo.RedirectStandardOutput = True
    pProcess.StartInfo.CreateNoWindow = True
    pProcess.Start()
    Dim strOutput As String = pProcess.StandardOutput.ReadToEnd()
    Dim substrings As String() = strOutput.Split("-"c)

    If substrings.Length >= 8 Then
        macAddress = substrings(3).Substring(Math.Max(0, substrings(3).Length - 2)) & "-" & substrings(4) & "-" & substrings(5) & "-" & substrings(6) & "-" & substrings(7) & "-" & substrings(8).Substring(0, 2)
        Return macAddress
    Else
        Return "not found"
    End If
End Function

Private Function GetMachineName(ByVal ipAdress As String) As String
    Dim machineName As String = String.Empty

    Try
        Dim hostEntry As IPHostEntry = Dns.GetHostEntry(ipAdress)
        machineName = hostEntry.HostName
    Catch ex As Exception
    End Try

    Return machineName
End Function

Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        If Not String.IsNullOrEmpty(e.Row.Cells(4).Text) Then
            If e.Row.Cells(4).Text = "On" Then
                e.Row.Cells(4).ForeColor = System.Drawing.Color.Black
                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
            Else
                e.Row.Cells(4).ForeColor = System.Drawing.Color.Black
                e.Row.Cells(4).BackColor = System.Drawing.Color.Red
            End If
        End If
    End If
End Sub

Screenshot