Network tools (1) Get all IPs of the intranet

1. Get all intranet IPs (excluding local IPs)

There are many related calculation methods on the Internet, such as calculation by enumeration, but I personally think this method is not good. Fortunately, there is the arp-a command of cmd,

Principle Call the arp-a command of cmd, and then parse it into the required data

Static class LANIpAllTool   (public static class LANIpAllTool)

        /// <summary>
        /// Use the CMD command to get all the IPs in the LAN
        /// </summary>
        /// <returns></returns>
        public static string GetAll()
        {
            var str = RunCmd("arp -a");
            var regex = new Regex(
                @"\s*(([0-9]{0,3}[.]?){4}\s)\s*(([a-zA-Z0-9]{2}[-]?){6}\s)\s*([\u4e00-\u9fa5]{0,4}\s)",
                RegexOptions.IgnoreCase);
            var match = regex.Matches (str);
            return match.Cast<object>().Aggregate("", (current, ma) => current + ma.ToString());
        }


        /// <summary>
        /// Execute the CMD statement
        /// </summary>
        /// <param name="cmd">CMD command to execute</param>
        public static string RunCmd(string cmd)
        {
            var pro = new Process
            {
                StartInfo =
                {
                    CreateNoWindow = true,
                    FileName = "cmd.exe",
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true
                }
            };
            pro.Start();
            pro.StandardInput.WriteLine(cmd);
            pro.StandardInput.WriteLine("exit");
            var outStr = pro.StandardOutput.ReadToEnd();
            pro.Close();
            return outStr;
        }

The following method serves the first method

transfer

        this.textBox2.Text = LANIpAllTool.RunCmd("arp -a");
        this.textBox3.Text= LANIpAllTool.GetAll();

Effect 

Display the results, one is the unprocessed data, the other is the processed data

What kind of structure is needed, it can be processed in

2. Get the local IP

        /// <summary>
        /// Get the local IP
        /// </summary>
        /// <returns></returns>
        public static string LocalIp()
        {
            var str=RunCmd("ipconfig");
            var regex = new Regex(@"\s*IPv4.*[:]\s*(([0-9]{1,3}[.]?){4})",RegexOptions.IgnoreCase);
            var match = regex.Matches (str);
            return (from object ma in match select Regex.Replace(ma.ToString(), @"(([.]\s)|\s|[\u4e00-\u9fa5]{0,}|[:]|[a-zA-Z]*[4]?|[IPv4])", "").Replace("IPv4:", "")).FirstOrDefault();
        }

Note: The following code is to call the above RunCmd() method

var str=RunCmd("ipconfig");




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325627514&siteId=291194637
Recommended