您的位置首页生活百科

C# 局域网IP扫描小工具

C# 局域网IP扫描小工具

的有关信息介绍如下:

C# 局域网IP扫描小工具

这是本人学习中分享

希望共同学习进步

通过ping获取局域网已被使用IP

添加2个Label、2个textBox、1个listBox、1个progressBar

程序所有代码

using System.Text.RegularExpressions;using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Net;

using System.Net.NetworkInformation;

using System.Text.RegularExpressions;

namespace 局域网IP扫描

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

string StartIPAddress = "";

string EndIPAddress = "";

//开始扫描地址

int intStrat = 0;

//终止扫描地址

int intEnd = 0;

private void button1_Click(object sender, EventArgs e)

{

listBox1.Items.Clear();

//开始扫描IP地址

StartIPAddress = textBox1.Text;

//终止扫描IP地址

EndIPAddress = textBox2.Text;

//开始扫描地址

intStrat = Int32.Parse(StartIPAddress.Substring(StartIPAddress.LastIndexOf(".") + 1));

//终止扫描地址

intEnd = Int32.Parse(EndIPAddress.Substring(EndIPAddress.LastIndexOf(".") + 1));

//指定进度条最大值

progressBar1.Minimum = intStrat;

//指定进度条最小值

progressBar1.Maximum = intEnd - 1;

//指定进度条初始值

progressBar1.Value = progressBar1.Minimum;

//如果开始扫描textbox为IP地址

if (isIp(textBox1.Text.Trim()))

{

button1.Enabled = false;

if (intEnd < intStrat)

{

MessageBox.Show("终止扫描地址小于起始扫描地址");

button1.Enabled = true;

return;

}

if (isIp(textBox2.Text.Trim()))

{

try

{

for (int i = intStrat; i < intEnd; i++)

{

Ping myping;

myping = new Ping();

myping.PingCompleted += new PingCompletedEventHandler(pingIpStatus);

string pingIp = textBox1.Text.ToString().Substring(0, textBox1.Text.ToString().LastIndexOf(".") + 1) + i.ToString();

myping.SendAsync(pingIp,1000,null);

progressBar1.Value = i;

}

button1.Enabled = true;

}

catch

{

button1.Enabled = true;

}

}

else

{

//输入IP地址非法

MessageBox.Show("结束扫描IP地址非法","错误",MessageBoxButtons.OK,MessageBoxIcon.Error );

button1.Enabled = true;

}

}

else

{

//输入IP地址非法

MessageBox.Show("开始扫描IP地址非法", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

button1.Enabled = true;

}

}

#region 判断是否为IP地址

///

/// 验证IP地址是否合法

///

/// 要验证的IP地址

///

public static bool isIp(string ip)

{

//如果为空,认为验证不合格

if (string.IsNullOrEmpty(ip))

{

return false;

}

//清除要验证字符传中的空格

ip = ip.Trim();

//模式字符串,正则表达式

string patten = @"^((2\d|25|?\d\d?)\.){3}(2\d|25|?\d\d?)$";

//验证

return Regex.IsMatch(ip, patten);

}

#endregion

#region ping 局域网内IP地址状态

private void pingIpStatus(object sender, PingCompletedEventArgs e)

{

//如果ping 返回状态为 OK

if (e.Reply.Status == IPStatus.Success)

{

listBox1.Items.Add("IP地址:" + e.Reply.Address.ToString());

}

}

#endregion

}

}