日期:2014-05-18  浏览次数:20840 次

c#实现验证某个IP地址是否能ping通
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.NetworkInformation;
using System.Threading;
namespace Manager.Common
{
public static class NetCommon{
        /// <summary>
        /// 验证IP地址字符串的正确性
        /// </summary>
        /// <param name="strIP">要验证的IP地址字符串</param>
        /// <returns>格式是否正确,正确为 true 否则为 false</returns>
        public static bool CheckIPAddr(string strIP)
        {
            if (string.IsNullOrEmpty(strIP))
            {
                return false;
            }
            // 保持要返回的信息
            bool bRes = true;
            int iTmp = 0;    // 保持每个由“.”分隔的整型
            string[] ipSplit = strIP.Split('.');
            if (ipSplit.Length < 4 || string.IsNullOrEmpty(ipSplit[0]) ||
                string.IsNullOrEmpty(ipSplit[1]) ||
                string.IsNullOrEmpty(ipSplit[2]) ||
                string.IsNullOrEmpty(ipSplit[3]))
            {
                bRes = false;
            }
            else
            {
                for (int i = 0; i < ipSplit.Length; i++)
                {
                    if (!int.TryParse(ipSplit[i], out iTmp) || iTmp < 0 || iTmp > 255)
                    {
                        bRes = false;
                        break;
                    }
                }
            }

            return bRes;
        }
        /// <summary>
        /// 验证某个IP是否可ping通