C# 实现Ping

 

 

 

核心代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Text;

 

//.... 

    //arg为主机IP,timeout为连接超时的时间,packSize为封包的大小

    private string PingHost(string arg, int timeout, int packSize)
    {        
         string data=MakeString(packSize);        
         Ping pingSender = new Ping ();           
            byte[] buffer = Encoding.ASCII.GetBytes (data);
            PingReply reply = pingSender.Send(arg, timeout, buffer);
           
            if (reply.Status == IPStatus.Success)
            {
             string hInfo = "";
             hInfo +="回复源:"+ reply.Address.ToString();
             hInfo +="/n  用时:" + (reply.RoundtripTime).ToString() + " ms";
             hInfo +="/n  接收到:" + (reply.Buffer.Length).ToString() + " Byte";
             return hInfo;             
            }
            else return "连接主机失败";
    }
   
   private string MakeString(int Length)
  {
        string baseString ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int len = baseString.Length;
        Random rnd = new Random();
        StringBuilder result = new StringBuilder();       
        for(int i=0; i<Length; i++)
           {
             result.Append(baseString.Substring(rnd.Next(len),1));            
           }     
      return result.ToString();     
  }

 

//调用PingHost方法就可以

//我是在.NET Framework 3.5调试的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值