C # Get a beginner of LAN IP, MAC address, and Port

Source: Internet
Author: User
Tags echo message ip number

First of all, thank Melou for the http://www.cnblogs.com/luoht/archive/2009/12/18/1627431.html of the essay, for Beginners of C # I, reference your essay on my study is really a great help.

C # Several ways to traverse a local area network:

1, the Microsoft Community describes the use of active Directory to traverse the local area network

Let's start by understanding what the DirectoryEntry class is.

namespaces: System.DirectoryServices
Assemblies: System.DirectoryServices (in System.DirectoryServices.dll)

The DirectoryEntry class encapsulates nodes or objects in an active Directory domain service hierarchy.

Where there are constructors

DirectoryEntry (String) Initializes a new instance of the DirectoryEntry class that binds this instance to a node in the Active Directory domain service at the specified path.

Links: https://msdn.microsoft.com/zh-cn/library/system.directoryservices.directoryentry.aspx

We must understand the active Directory in which

Using the Active directory (r) Domain Services (AD DS) server role, you can create a scalable, secure, and manageable infrastructure for user and resource management, and can provide access to directory-enabled applications such as Microsoft (R) Exchange Server) is supported.

AD DS provides a distributed database that can store and manage information about network resources and application-specific data in directory-enabled applications. The server running AD DS is called a domain controller. Administrators can use AD DS to organize network elements, such as users, computers, and other devices, into hierarchical inline structures. Inline hierarchies include Active Directory forests, domains in the forest, and organizational units (OUs) in each domain.

Links: https://technet.microsoft.com/zh-cn/library/hh831484.aspx

Next look at how to use DirectoryEntry

Using the DirectoryEntry component to view the network

        C # Operations WinNT Local Users and Groups        directoryentry demain = new DirectoryEntry ("WinNT:");            foreach (DirectoryEntry degroup in Demain.children)            {                //if the same as the selected user group if                (DEGroup.Name.ToLower () = = Comb_ Workgroup. Text.tolower ())                {                    //read out each host name under the user group                    foreach (DirectoryEntry decomputer in Degroup.children)                    {                        / /filter out Invalid results Computer:schema                        if (DEComputer.Name.ToLower ()! = "Schema")                        {                            listb_computer. Items.Add (Decomputer.name);}}}            

Effect evaluation: Slow speed, low efficiency, there is an invalid result computer:schema use the process of attention.

2, using dns.gethostbyaddress and Iphostentry traverse LAN

Dns.gethostbyaddress class: returns the Internet protocol (IP) address of the specified host.

namespaces: System.Net
Assemblies: System (in System.dll)

public static ipaddress[] Gethostaddresses (string hostnameoraddress)

Iphostentry class: provides a container class for Internet host address information.

namespaces: System.Net
Assemblies: System (in System.dll)

private void EnumComputers2 ()        {            //from 192.168.0.1 to 192.168.0.255 starts with the for            (int i = 1; I <= 255; i++)            {
   string Scanip = "192.168.0." + i.tostring ();                IPAddress Myscanip = Ipaddress.parse (Scanip);                Iphostentry myscanhost = null;                Try                {                    //Get Myscanip IP address                    myscanhost = dns.gethostbyaddress (Myscanip);                }                Catch                {                    continue;                }                if (myscanhost! = null)                {                    //returns IP and host name                    Console.WriteLine (Scanip + "|" + Myscanhost.hostname);}            }        

Effect evaluation: Low efficiency, slow speed, not generally slow.

3, using System.Net.NetworkInformation.Ping to traverse LAN

System.Net.NetworkInformation.Ping class: allows an application to determine whether a remote computer can be accessed over the network.

namespaces: System.Net.NetworkInformation
Assemblies: System (in System.dll)

        delegate void WT (int n);        Thread T;            private string Getmacaddress (string hostip)//Get the MAC address of the remote IP (cannot cross the network segment) {string mac = "";  try {Int32 ldest = inet_addr (HostIP);//Convert IP address from point format to unsigned long integer Int64 macinfo = new                Int64 ();                Int32 len = 6;                The SENDARP function sends an Address Resolution protocol (ARP) request to obtain the physical address corresponding to the specified destination IPv4 address sendarp (ldest, 0, ref macinfo, ref Len); String Tmpmac = Convert.ToString (Macinfo, 16). PadLeft (12, ' 0 ');//Convert to 16 binary note some do not have 12-bit MAC = tmpmac.substring (0, 2). ToUpper ();//for (int i = 2; i < tmpmac.length; i = i + 2) {Mac = Tmp Mac.substring (i, 2).                ToUpper () + "-" + Mac;            }} catch (Exception mye) {mac = "Get the MAC error of the remote host:" + mye.message;        } return MAC; }private void enumcomputers (int n) {//lock (this)//invoke (New MethodInvoker (delegate ()//{//Registered Commission if (this.txtAddrs.InvokeReq                uired) {WT d = new WT (enumcomputers); This.            Invoke (d, new object[] {n});                    } else {try {for (int i = 0; I <= 255; i++)                        {Ping myping;                        myping = new Ping ();                        Occurs when an asynchronous operation that sends an INTERNET Control Message Protocol (ICMP) echo message and receives the corresponding ICMP echo reply message is completed or canceled.                        myping.pingcompleted + = new Pingcompletedeventhandler (myping_pingcompleted);                        String PINGIP = "192.168." + n.tostring () + "." + i.tostring ();                        Attempts to asynchronously send an Internet Control Message Protocol (ICMP) echo message to the specified computer and receive the corresponding ICMP echo reply message from the computer.                    Myping.sendasync (PINGIP, +, NULL);              }} catch (Exception ex) {      MessageBox.Show (ex.                Message);        }            }            //})); }private void Myping_pingcompleted (object sender, Pingcompletedeventargs e) {StringBuilder sb = new STR            Ingbuilder (); if (E.reply.status = = ipstatus.success) {sb.                Append ("IP:" + e.reply.address.tostring () + "\ r \ n");                Get MAC address String mac = Getmacaddress (e.reply.address.tostring ()); Sb.                Append ("Mac:" + mac + "\r\n\r\n");            num++; } This.txtAddrs.Text + = sb.            ToString (); This.lbIPs.Text = "Online IP number:" + Num.            ToString (); This.lbIPs.Text = num.        ToString ();            } private void Button2_Click (object sender, EventArgs e) {this.txtAddrs.Text = "";                     num = 0;            t = new Thread (() = Enumcomputers ((int) (this.txtIP2.Value)));            T.isbackground = true;            T.start (); Enumcomputers((int) (this.txtIP2.Value)); }

C # Get a beginner of LAN IP, MAC address, and Port

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.