c# 网站检测
2009-03-24 11:38:00 susubuhui 阅读数 1716

 
以下的代码的原作是opensource的一个叫sniffer.net的,用vb.net写的,这里只是简单的用c#翻译了一下,暂时还只能监控所有数据包,不能监控某一个进程的数据包,代码如下:
using system;
using system.text;
using system.net;
using system.net.sockets;
using system.runtime.interopservices;

namespace updatetester
{
/**//// <summary>
/// monitor 的摘要说明。
/// </summary>
public class monitor
{
public delegate void newpacketeventhandler(monitor m, packet p);
public event newpacketeventhandler newpacket;
private socket m_monitor;
private ipaddress m_ip;
private byte[] m_buffer = new byte[65535];
private const system.int32 ioc_vendor = 0x18000000;
private const int ioc_in = -2147483648;
private const int sio_rcvall = ioc_in ^ ioc_vendor ^ 1;
private const int security_builtin_domain_rid = 0x20;
private const int domain_alias_rid_admins = 0x220;

public system.net.ipaddress ip
{
get { return m_ip; }
}

public byte[] buffer
{
get { return m_buffer; }
}

public monitor()
{
//
// todo: 在此处添加构造函数逻辑
//
}

public monitor(ipaddress ipaddress)
{
if (!(environment.osversion.platform == platformid.win32nt) && environment.osversion.version.major<5)
{
throw new notsupportedexception("this program requires windows 2000, windows xp or windows .net server!");
}
m_ip = ipaddress;
}

public void start()
{
if (m_monitor==null)
{
try
{
m_monitor = new socket(addressfamily.internetwork, sockettype.raw, protocoltype.ip);
m_monitor.bind(new ipendpoint(ip, 0));
m_monitor.iocontrol(sio_rcvall, bitconverter.getbytes(1), null);
m_monitor.beginreceive(m_buffer, 0, m_buffer.length, socketflags.none, new asynccallback(onreceive), null);
}
catch (exception e)
{
m_monitor = null;
throw new socketexception();
}
}
}

public void stop()
{
if (m_monitor!=null)
{
m_monitor.close();
}
m_monitor = null;
}

public void onreceive(system.iasyncresult ar)
{
try
{
int received = m_monitor.endreceive(ar);

try
{
if (m_monitor!=null)
{
byte[] pkt = new byte[received];
array.copy(buffer, 0, pkt, 0, received);
onnewpacket(new packet(pkt, datetime.now));
}
}
catch(exception e)
{
throw;
}

m_monitor.beginreceive(buffer, 0, buffer.length, socketflags.none, new asynccallback(onreceive), null);
}
catch (exception e)
{

}
}

protected void onnewpacket(packet p)
{
newpacket(this, p);
}
}
}


using system;
using system.text;
using system.net;
using system.net.sockets;

namespace updatetester
{

public enum precedence
{
routine = 0,
priority = 1,
immediate = 2,
flash = 3,
flashoverride = 4,
criticecp = 5,
internetworkcontrol = 6,
networkcontrol = 7
}

public enum delay
{
normaldelay = 0,
lowdelay = 1
}

public enum throughput
{
normalthroughput = 0,
highthroughput = 1
}

public enum reliability
{
normalreliability = 0,
highreliability = 1
}

public enum protocol
{
ggp = 3,
icmp = 1,
idp = 22,
igmp = 2,
ip = 4,
nd = 77,
pup = 12,
tcp = 6,
udp = 17,
other = -1
}
/**//// <summary>
/// packet 的摘要说明。
/// </summary>
public class packet
{

private byte[] m_raw;
private datetime m_time;
private int m_version;
private int m_headerlength;
private precedence m_precedence;
private delay m_delay;
private throughput m_throughput;
private reliability m_reliability;
private int m_totallength;
private int m_identification;
private int m_timetolive;
private protocol m_protocol;
private byte[] m_checksum;
private string m_sourceaddress;
private string m_destinationaddress;
private int m_sourceport;
private int m_destinationport;

public packet()
{
//
// todo: 在此处添加构造函数逻辑
//
}
//
// public packet(byte[] raw):(byte[] raw, datetime time)
// {
// packet(raw, datetime.now);
// }

public packet(byte[] raw, datetime time)
{
if (raw==null)
{
throw new argumentnullexception();
}
if (raw.length<20)
{
throw new argumentexception();
}

this.m_raw = raw;
this.m_time = time;
this.m_headerlength = (raw[0] & 0xf) * 4;
if ((raw[0] & 0xf) < 5) {throw new argumentexception();}
this.m_precedence = (precedence)((raw[1] & 0xe0) >> 5);
this.m_delay = (delay)((raw[1] & 0x10) >> 4);
this.m_throughput = (throughput)((raw[1] & 0x8) >> 3);
this.m_reliability = (reliability)((raw[1] & 0x4) >> 2);
this.m_totallength = raw[2] * 256 + raw[3];
if ( ! (this.m_totallength == raw.length)) { throw new argumentexception();} // invalid size of packet;
this.m_identification = raw[4] * 256 + raw[5];
this.m_timetolive = raw[8];

m_protocol = (protocol)raw[9];

m_checksum = new byte[2];
m_checksum[0] = raw[11];
m_checksum[1] = raw[10];

try
{
m_sourceaddress = getipaddress(raw, 12);
m_destinationaddress = getipaddress(raw, 16);
}
catch (exception e)
{
throw;
}

if (m_protocol == protocol.tcp || m_protocol == protocol.udp)
{
m_sourceport = raw[m_headerlength] * 256 + raw[m_headerlength + 1];
m_destinationport = raw[m_headerlength + 2] * 256 + raw[m_headerlength + 3];
}
else
{

m_sourceport = -1;
m_destinationport = -1;
}
}

public string getipaddress(byte[] barray, int nstart)
{
byte[] tmp = new byte[4];

if (barray.length > nstart + 2)
{
tmp[0] = barray[nstart];
tmp[1] = barray[nstart + 1];
tmp[2] = barray[nstart + 2];
tmp[3] = barray[nstart + 3];
}

return tmp[0] + "." + tmp[1] + "." + tmp[2] + "." + tmp[3];
}

public int totallength
{
get { return m_totallength; }
}

public datetime time
{
get { return this.m_time; }
}

public protocol protocol
{
get { return this.m_protocol; }
}

public string sourceaddress
{
get { return this.m_sourceaddress; }
}

public string source
{
get
{
if ( m_sourceport != -1 )
{
return sourceaddress.tostring() + ":" + m_sourceport.tostring();
}
else
{
return sourceaddress.tostring();
}
}
}

public string destination
{
get
{
if (this.m_destinationport != -1)
{
return destinationaddress.tostring() + ":" + m_destinationport.tostring();
}
else
{
return destinationaddress.tostring();
}
}
}

public string destinationaddress
{

get
{
return m_destinationaddress;
}
}
}
}


在主程序里
private monitor[] m_packetmonitors;
private arraylist m_packets;
private system.windows.forms.statusbar statusbar1;
private int m_packetssize;

执行方法中
private void startmonitor()
{
ipaddress[] hosts = dns.resolve(dns.gethostname()).addresslist;

if (hosts.length == 0) { throw new notsupportedexception("this computer does not have non-loopback interfaces installed!");}
for (int i=0; i<hosts.length; i++)
{
}

m_packetmonitors = new monitor[1];
m_packets = new arraylist();
m_packetmonitors[0] = new monitor(hosts[0]);

// 添加代理,每次有新的packet到时都出发下面哪个动作
m_packetmonitors[0].newpacket+=new monitor.newpacketeventhandler(this.onnewpacket);
m_packetmonitors[0].start();
}

// 这个方法用于把packet显示到一个地方

private void onnewpacket(monitor m, packet p)
{
m_packets.add(p);
m_packetssize += p.totallength;
try
{
txtlog.text += p.time.tostring()+p.protocol.tostring()+p.source.tostring()+p.destination.tostring()+p.totallength.tostring();

}
catch (exception e)
{
messagebox.show(e.message);
}

statusbar1.text = string.format("intercepted {0} packet(s) [{1} bytes]", m_packets.count, m_packetssize);
}

 

2015-12-27 11:15:51 QingHeShiJiYuan 阅读数 301
using System.Net.NetworkInformation;
  
Ping ping = new Ping();
            try
            {
                PingReply reply = ping.Send("www.baidu.com");

                if (reply.Status == IPStatus.Success)
                {
                    Image img = Image.FromFile("Success.png");
                    pictureBox1.Image = img;

                    label1.Text = "网络连接正常";
                }
            }
            catch (Exception)
            {
                Image img = Image.FromFile("Fail.png");
                pictureBox1.Image = img;

                label1.Text = "网络连接超时";

            }

2017-04-14 10:07:25 nihang1234 阅读数 1535

转自:原作者
由于工作中需要检测优盘是否存在,读取优盘中的文件,所有在此记录。


把优盘的信息读取封装到一个类:

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace TempControl.Classes
{
    internal class FlashDisk
    {
        private const int WmDeviceChange = 0x219;//U盘插入后,OS的底层会自动检测到,然后向应用程序发送“硬件设备状态改变“的消息
        private const int DbtDeviceArrival = 0x8000;  //就是用来表示U盘可用的。一个设备或媒体已被插入一块,现在可用。
        private const int DbtConfigChangeCanceled = 0x0019;  //要求更改当前的配置(或取消停靠码头)已被取消。
        private const int DbtConfigchanged = 0x0018;  //当前的配置发生了变化,由于码头或取消固定。
        private const int DbtCustomEvent = 0x8006; //自定义的事件发生。 的Windows NT 4.0和Windows 95:此值不支持。
        private const int DbtDeviceQueryRemove = 0x8001;  //审批要求删除一个设备或媒体作品。任何应用程序也不能否认这一要求,并取消删除。
        private const int DbtDeviceQueryRemoveFailed = 0x8002;  //请求删除一个设备或媒体片已被取消。
        private const int DbtDeviceRemoveComplete = 0x8004;  //一个设备或媒体片已被删除。
        private const int DbtDeviceRemovePending = 0x8003;  //一个设备或媒体一块即将被删除。不能否认的。
        private const int DbtDeviceTypeSpecific = 0x8005;  //一个设备特定事件发生。
        private const int DbtDevNodesChanged = 0x0007;  //一种设备已被添加到或从系统中删除。
        private const int DbtQueryChangeConfig = 0x0017;  //许可是要求改变目前的配置(码头或取消固定)。
        private const int DbtUserDefined = 0xFFFF;  //此消息的含义是用户定义的

        public static string[] GetRemovableDrivers(ref Message m)
        {
            try
            {
                if (m.Msg != WmDeviceChange) return null;

                switch (m.WParam.ToInt32())
                {
                    case WmDeviceChange:
                        break;
                    case DbtDeviceArrival://检测到U盘插入
                    case DbtDeviceRemoveComplete: //检测到U盘拔出
                        var driveInfos = DriveInfo.GetDrives();

                        var flashDisks = from driveInfo in driveInfos
                                         where driveInfo.DriveType == DriveType.Removable
                                         select driveInfo.Name;
                        return flashDisks.ToArray();
                    case DbtConfigChangeCanceled:
                        break;
                    case DbtConfigchanged:
                        break;
                    case DbtCustomEvent:
                        break;
                    case DbtDeviceQueryRemove:
                        break;
                    case DbtDeviceQueryRemoveFailed:
                        break;
                    case DbtDeviceRemovePending:
                        break;
                    case DbtDeviceTypeSpecific:
                        break;
                    case DbtQueryChangeConfig:
                        break;
                    case DbtUserDefined:
                        break;
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }
    }


}

在窗体中调用,重写窗体的protected override void WndProc(ref Message m)函数:

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        try
        {
            var aa = FlashDisk.GetRemovableDrivers(ref m);
            if (aa == null || aa.Length < 1) return;

            var ds = string.Empty;
            for (int i = 0; i < aa.Length; i++)
            {
                ds += aa[i] + Environment.NewLine;
            }

            Console.WriteLine(ds);
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }

    }

运行中发行如果把base.WndProc(ref m);这行代码放到最下面,运行中报错“创建窗口句柄失败”。原来if (aa == null || aa.Length < 1) return;这个代码导致``base.WndProc(ref m);不能总是得到执行。分析得知窗口的句柄创建是通过这行代码创建的。


心得:

在定时器中直接调用DriveInfo.GetDrives()函数通过判断driveInfo.DriveType == DriveType.Removable实时性更好

2019-06-11 22:33:17 PeterZhuGe 阅读数 63
/// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary>
        /// 检查危险字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string Filter(string sInput)
        {
            if (sInput == null || sInput == "")
                return null;
            string sInput1 = sInput.ToLower();
            string output = sInput;
            string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            {
                throw new Exception("字符串中含有非法字符!");
            }
            else
            {
                output = output.Replace("'", "''");
            }
            return output;
        }

        /// <summary> 
        /// 检查过滤设定的危险字符
        /// </summary> 
        /// <param name="InText">要过滤的字符串 </param> 
        /// <returns>如果参数存在不安全字符,则返回true </returns> 
        public static bool SqlFilter(string word, string InText)
        {
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }

 

2015-10-08 20:14:35 QingHeShiJiYuan 阅读数 767
<pre name="code" class="csharp">            string url = "www.baidu.com";


            Ping ping = new Ping();


            try
            {
                int timeout=3;//设置超时时间


                PingReply pr = ping.Send(url,timeout);


                if (pr.Status == IPStatus.Success)
                    MessageBox.Show("连接正常!");


                if (pr.Status == IPStatus.TimedOut)
                    MessageBox.Show("连接超时!");
            }
            catch (Exception)
            {


                MessageBox.Show("连接失败!");
            }



                            

C#检测键盘输入

阅读数 1

C#学习网站

阅读数 350

C#学习网站

阅读数 0

c#学习网站

阅读数 400

C#学习网站

阅读数 13

没有更多推荐了,返回首页