- [VB.NET] Lấy địa chỉ Bios Serial Number trên Winform
- [C#] Giới thiệu và sử dụng thư viện AutoMapper
- [DEVEXPRESS] Hướng dẫn Custom Summary in Footer trong Gridview C#
- [C#] Dependency Injection in Winform
- [SQLSERVER] Hướng dẫn tìm kiếm nâng cao trên sql
- [C#] Hướng dẫn sử dụng SetTimeOut trên Winform like Javascript
- [DATABASE] In cây thông noel bằng sqlserver
- [C#] Hướng dẫn fix lỗi hiển thị UTF-8 khi sử dụng WebClient Download String
- [DATABASE] Hướng dẫn mã hóa và giải mã sử dụng thuật toán AES 256 trên sqlserver
- [DATABASE] Base64 Encode and Decode trong Sqlserver
- [C#] Vì Mẹ anh bắt phải Fake địa chỉ MacAddress
- [C#] Hướng dẫn xuất dữ liệu từ DataGridview ra file Excel
- [C#] Hướng dẫn khởi động lại chương trình ứng dụng winform
- [C#] Sự khác nhau giữa String.IsNullOrEmpty và String.IsNullOrWhiteSpace
- [C#] Hướng dẫn đọc file hình ảnh định dạng WEBP và chuyển đổi WebP sang JPG
- [C#] Kiểm tra phiên bản Microsoft Office đang sử dụng trên máy tính
- [C#] Hướng dẫn chuyển đổi tập tin hình ảnh XPS sang Bitmap
- [C#] Giới thiệu Component WebView2 của Microsoft
- [C#] Hướng dẫn lưu tất cả hình ảnh từ File Excel vào thư mục window
- [DATABASE] Hướng dẫn import và export hình ảnh image từ Sqlserver
[C#] Hướng dẫn viết ứng dụng Scan IP, MAC, Machine Name trong mạng Lan Network
Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách scan toàn bộ Ip cùng lớp mạng trong mạng LAN, lấy địa chỉ Mac Address, và tên Machine Name của IP đó trong lập trình C#.
[C#] Scan IpAddress, Mac Address, Machine Name in Lan Network
Trong bài viết này, mình sử dụng lệnh trong MS-DOS
Arp -a
Trong MS-DOS, các bạn gõ vào lệnh Arp -a để xem kết quả như hình bên dưới:
Để lấy các thông tin các máy tính trong mạng Lan, sau đó, chúng ta sẽ sử dụng Regular Expression để tách địa chỉ IP Address và Mac Address.
Sau khi, có được địa chỉ Ip Address, chúng ta sẽ phân giải địa chỉ Ip sang Hostname (lưu ý: ở bước này phân giải hơi chậm).
Ở hình bên trên, các bạn thấy phần Type bao gồm: dynamic và static, trong bài viết mình chỉ lấy Dynamic thôi nhé.
Dưới đây, là giao diện demo ứng dụng:
Source code Scan IP in Lan Network C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(new Action(() => {
listView1.Items.Clear();
var data = GetAllMacAddressesAndIppairs();
int i = 0;
foreach (var x in data)
{
i++;
ListViewItem item = new ListViewItem(new string[] { i.ToString(), x.IPAddress, x.MacAddress, x.HostName });
listView1.BeginInvoke(new Action(() => {
listView1.Items.Add(item);
}));
}
}));
}
public string getMacByIp(string ip)
{
var macIpPairs = GetAllMacAddressesAndIppairs();
int index = macIpPairs.FindIndex(x => x.IPAddress == ip);
if (index >= 0)
{
return macIpPairs[index].MacAddress.ToUpper();
}
else
{
return null;
}
}
public List GetAllMacAddressesAndIppairs()
{
List mip = new List();
Process pProcess = new Process();
pProcess.StartInfo.FileName = "arp";
pProcess.StartInfo.Arguments = "-a ";
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Start();
string cmdOutput = pProcess.StandardOutput.ReadToEnd();
string pattern = @"(?([0-9]{1,3}.?){4})s*(?([a-f0-9]{2}-?){6})s*(?([a-zA-Z]){3})";
foreach (Match m in Regex.Matches(cmdOutput, pattern, RegexOptions.IgnoreCase))
{
string type = m.Groups["type"].Value;
if (type.ToLower().Equals("dyn"))
{
string machine_name = GetMachineNameFromIPAddress(m.Groups["ip"].Value);
mip.Add(new IPInfo(m.Groups["mac"].Value, m.Groups["ip"].Value));
}
}
return mip;
}
public static String ReverseIPLookup(IPAddress ipAddress)
{
if (ipAddress.AddressFamily != AddressFamily.InterNetwork)
throw new ArgumentException("IP address is not IPv4.", "ipAddress");
var domain = String.Join(
".", ipAddress.GetAddressBytes().Reverse().Select(b => b.ToString())
) + ".in-addr.arpa";
return DnsGetPtrRecord(domain);
}
static String DnsGetPtrRecord(String domain)
{
const Int16 DNS_TYPE_PTR = 0x000C;
const Int32 DNS_QUERY_STANDARD = 0x00000000;
const Int32 DNS_ERROR_RCODE_NAME_ERROR = 9003;
IntPtr queryResultSet = IntPtr.Zero;
try
{
var dnsStatus = DnsQuery(
domain,
DNS_TYPE_PTR,
DNS_QUERY_STANDARD,
IntPtr.Zero,
ref queryResultSet,
IntPtr.Zero
);
if (dnsStatus == DNS_ERROR_RCODE_NAME_ERROR)
return null;
if (dnsStatus != 0)
throw new Win32Exception(dnsStatus);
DnsRecordPtr dnsRecordPtr;
for (var pointer = queryResultSet; pointer != IntPtr.Zero; pointer = dnsRecordPtr.pNext)
{
dnsRecordPtr = (DnsRecordPtr)Marshal.PtrToStructure(pointer, typeof(DnsRecordPtr));
if (dnsRecordPtr.wType == DNS_TYPE_PTR)
return Marshal.PtrToStringUni(dnsRecordPtr.pNameHost);
}
return null;
}
finally
{
const Int32 DnsFreeRecordList = 1;
if (queryResultSet != IntPtr.Zero)
DnsRecordListFree(queryResultSet, DnsFreeRecordList);
}
}
[DllImport("Dnsapi.dll", EntryPoint = "DnsQuery_W", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
static extern Int32 DnsQuery(String lpstrName, Int16 wType, Int32 options, IntPtr pExtra, ref IntPtr ppQueryResultsSet, IntPtr pReserved);
[DllImport("Dnsapi.dll", SetLastError = true)]
static extern void DnsRecordListFree(IntPtr pRecordList, Int32 freeType);
[StructLayout(LayoutKind.Sequential)]
struct DnsRecordPtr
{
public IntPtr pNext;
public String pName;
public Int16 wType;
public Int16 wDataLength;
public Int32 flags;
public Int32 dwTtl;
public Int32 dwReserved;
public IntPtr pNameHost;
}
private string GetMachineNameFromIPAddress(string ipAdress)
{
string machineName = string.Empty;
try
{
IPHostEntry hostEntry = Dns.GetHostEntry(ipAdress);
machineName = hostEntry.HostName;
}
catch (Exception ex)
{
}
return machineName;
}
public class IPInfo
{
public IPInfo(string macAddress, string ipAddress)
{
this.MacAddress = macAddress;
this.IPAddress = ipAddress;
}
public string MacAddress { get; private set; }
public string IPAddress { get; private set; }
private string _HostName = string.Empty;
public string HostName
{
get
{
Task t = Task.Factory.StartNew(new Action(() => {
if (string.IsNullOrEmpty(this._HostName))
{
try
{
this._HostName = ReverseIPLookup(System.Net.IPAddress.Parse( this.IPAddress));
}
catch
{
this._HostName = string.Empty;
}
}
}));
t.Wait();
return this._HostName;
}
}
}
}
}
Các bạn, có thể download source code bên dưới để tham khảo.
HAPPY CODING