C#获取局域网中的所有正在使用的IP地址
方法不是很好。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Text.RegularExpressions; namespace _12获取局域网中的所有IP地址 { class Program { static void Main(string[] args) { IPAddress startIP = InputIPAddress("请输入开始IP地址:"); IPAddress endIP = InputIPAddress("请输入结束IP地址:"); int startNum; int endNum; string str1; string str2; GetBound(startIP, out startNum, out str1); GetBound(endIP, out endNum, out str2); if (str1 != str2) { Console.WriteLine("输入的IP不在同一段。"); return; } for (int i = startNum; i < endNum; i++) { try { IPAddress ip = IPAddress.Parse(str1 + i); Console.Write("[{0}] - [", ip); IPHostEntry hostEntry = Dns.GetHostEntry(ip); Console.WriteLine("{0}]", hostEntry.HostName); } catch (Exception e) { Console.WriteLine(e.Message + "]"); } } Console.ReadKey(); } static void Scan(IPAddress startIP, IPAddress endIP) { } static void GetBound(IPAddress ip, out int num, out string str) { string reg = @"(?<str>\d+\.\d+\.\d+\.)(?<num>\d+)"; Match match = new Regex(reg).Match(ip.ToString()); string numStr = match.Groups["num"].Value; num = Convert.ToInt32(numStr); str = match.Groups["str"].Value; } static IPAddress InputIPAddress(string msg) { string msgTemp = msg; IPAddress ip = null; while (true) { Console.Clear(); Console.WriteLine(msg); string ipStr = Console.ReadLine(); if (IPAddress.TryParse(ipStr, out ip)) { break; } else { msg = "输入的\"" + ipStr + "\"格式不正确," + msgTemp; } } Console.Clear(); return ip; } } }
如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)