c# 判斷一個ip通不通 能不能ping通

來源:互聯網
上載者:User

方法一: 已經證實能用的.

using System;<br />using System.Collections.Generic;<br />using System.ComponentModel;<br />using System.Data;<br />using System.Drawing;<br />using System.Text;<br />using System.Windows.Forms;<br />using System.Net;<br />using System.Net.NetworkInformation;</p><p>namespace PingIpAddress<br />{<br /> public partial class Form1 : Form<br /> {<br /> public Form1()<br /> {<br /> InitializeComponent();<br /> }</p><p> private void Form1_Load(object sender, EventArgs e)<br /> {</p><p> }<br /> private Ping pingSender = new Ping();<br /> private string strIP = "";<br /> private void button1_Click(object sender, EventArgs e)<br /> {<br /> strIP = txtIP.Text; //要ping的IP地址 第一種方法本人親自實驗過。可以使用<br /> PingOptions pingOption = new PingOptions();<br /> pingOption.DontFragment = true;</p><p> string data = "sendData:goodgoodgoodgoodgoodgood";<br /> byte[] buffer = Encoding.ASCII.GetBytes(data);<br /> int timeout = 120;<br /> PingReply reply = pingSender.Send(strIP, timeout, buffer);<br /> if (reply.Status == IPStatus.Success)<br /> {<br /> MessageBox.Show("能ping通 ");<br /> }<br /> else<br /> {<br /> MessageBox.Show("ping不通");<br /> }<br /> }<br /> }<br />}</p><p>

 

第二種方法: 沒試過

 

C#判斷網路狀態<br />代碼<br />/// <summary><br />/// 是否能 Ping 通指定的主機<br />/// </summary><br />/// <param name="ip">ip 地址或主機名稱或網域名稱</param><br />/// <returns>true 通,false 不通</returns><br />public bool Ping(string ip)<br />{<br /> int timeout = 1000;<br /> string data = "Test Data!";<br /> System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();<br /> System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();<br /> options.DontFragment = true; byte[] buffer = Encoding.ASCII.GetBytes(data);<br /> System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);<br /> if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false;<br />}</p><p>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.