C#操作IP地址

獲取本機IP

public static string GetLocalIP()
        {
            string strIP = string.Empty;
            try
            {
                string hostName = Dns.GetHostName();//主機名
                IPHostEntry ipEntry = Dns.GetHostEntry(hostName);
                for (int i = 0; i < ipEntry.AddressList.Length; i++)
                {
                    //從IP列表中篩選出IPV4類型的IP地址
                    if (ipEntry.AddressList[i].AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        strIP= ipEntry.AddressList[i].ToString();
                        break;
                    }
                }
            }
            catch (Exception)
            {

            }

            return strIP;
        }

檢查IP地址合法性

public static bool CheckIP(string strIP)
        {
            strIP = strIP.Replace(" ", "");//去除空格
            return Regex.IsMatch(strIP, @"^(([1-9]\d?)|(1\d{2})|(2[01]\d)|(22[0-3]))(\.((1?\d\d?)|(2[04]/d)|(25[0-5]))){3}$");
        }

驗證某個IP是否可以Ping通

public static bool TestNetConnectity(string strIP)
        {
            if (!CheckIP(strIP)) return false;

            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;

            string data = "test...test...test...test...test...test...";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 120;
            PingReply reply = pingSender.Send(strIP, timeout, buffer, options);
            return (reply.Status == IPStatus.Success);
        }

多次Ping一個IP地址,看是否一直能Ping通

public bool TestNetConnected(string strIP,int waitSeconds,int iTestTimes)
        {
            bool isConnected = true;

            for (int i = 0; i < iTestTimes; i++)
            {
                if (!TestNetConnectity(strIP)) isConnected = false;

                Thread.Sleep(waitSeconds * 1000);
            }

            return isConnected;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章