private void set_button1_Click(object sender, EventArgs e) { string hostname = textBox1.Text; ping = HPing.ObjectFactory(textBox1.Text); if (ping != null) { textBox2.Text = ping.GetTargetAddress(); } else { textBox2.Text = ""; } }
public static HPing ObjectFactory(string host){ HPing ping=new HPing(); try { ping.socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); ping.socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000); } catch (Exception) { MessageBox.Show("Raw Socket Creation failed, Are you a super-user?", "Error", MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } try{ ping.target= new IPEndPoint( Dns.GetHostEntry(host).AddressList[0],0); string hn=Dns.GetHostName(); IPHostEntry en = Dns.GetHostEntry(hn); IPAddress ipa=null; foreach (IPAddress ip in en.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ipa = ip; break; } } ping.remoteEp = new IPEndPoint(en.AddressList[5], 0); ping.socket.Bind(ping.remoteEp); }catch(Exception){ MessageBox.Show("Failed Bind,Is the Address sure?", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } ping.pid=(UInt16)(Process.GetCurrentProcess().Id); ping.oid=objectID++; QueryPerformanceFrequency(ref ping.freq); return ping; }