有点麻烦,socket连接问题
对当前客户机所在网段的IP扫描,因为提供侦听服务的机器不确定,但是是唯一存在的。
调用tempSocket.Connect(ipe);时,没有提供服务的机器会抛出错误,用try处理,也要等待很长时间,有没有什么方法可以快速判断连接是否成功的?
------解决方案--------------------用多线程,多个线程一起扫描,这样会看起来快一些!
------解决方案--------------------using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace 多线程扫描网段
{
public partial class Form1 : Form
{
private DateTime startTime;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int min = (int)this.numericUpDown4.Value,max = (int)this.numericUpDown5.Value;
if (min> = max) { MessageBox.Show( "网段输入错误! "); return; }
startTime = DateTime.Now;
string mask = this.numericUpDown1.Value.ToString() + ". " + this.numericUpDown2.Value.ToString() + ". " + this.numericUpDown3.Value.ToString();
this.progressBar1.Minimum = min;
this.progressBar1.Maximum = max;
Thread[] threads=new Thread[max-min +1];
while (min <= max)
{
Scan NewThreadScan = new Scan();
NewThreadScan.IP = mask + ". " + min.ToString();
NewThreadScan.GetHostInfo = new HostInfo(newHostInfo);
threads[min - 1] = new Thread(new ThreadStart(NewThreadScan.start));
threads[min - 1].Start();
min++;
}
}
public void newHostInfo(string HostIP, string NewHostName)
{
this.setListBox(HostIP, NewHostName);
}
private void setListBox(string HostIp, string NewHostName)
{
if (listBox1.InvokeRequired && label4.InvokeRequired && progressBar1.InvokeRequired)
{
HostInfo b = new HostInfo(setListBox);
Invoke(b, new object[] { HostIp, NewHostName });
}
else
{
lock (listBox1)
{
listBox1.Items.Add(HostIp + " " + NewHostName);
if (progressBar1.Value != progressBar1.Maximum)
{
progressBar1.Value++;
}
else
{
MessageBox.Show( "成功完成检测! ");
DateTime endTime = DateTime.Now;
TimeSpan timeSp = endTime - startTime;
label4.Text = timeSp.Seconds.ToString() + "秒 ";
progressBar1.Value = progressBar1.Minimum;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace 多线程扫描网段
{
class Scan
{
private string _IP;
public string _HostName;
public HostInfo GetHostInfo;
public string IP
{
get { return _IP; }
set { _IP = value; }