Re: Server Alive by anonymous
anonymous
Thu May 13 16:46:03 CDT 2004
Andrew
I tried the example you cited - it ALWAYS returns false even when in fact I am connected. I use the dos ping utility and it returns replies but when I use the code in that example it returns false. Here is the code, perhaps you or someone else could tell whats wrong
public class Pin
IPAddress hostadd
int timeout_ms
string last_error = ""
string resolved_ip_address = ""
// this is the default constructo
public Ping(
/
// TODO: Add constructor logic her
/
timeout_ms = 10000000; // 2s
// this constructor allows the timeout value to be specified
public Ping(int a_timeout_ms
/
// TODO: Add constructor logic her
/
timeout_ms = a_timeout_ms * 1000; // tmo in millisecond
// returns the last network erro
public string LastErro
ge
return last_error
public string IpAddres
ge
return resolved_ip_address
public bool CheckByNameOrIP(String vw_name
tr
// try to resolve the name using DN
hostadd = Dns.Resolve(vw_name).AddressList[0]
catch (System.Net.Sockets.SocketException ex
last_error = ex.Message
return false
return local_ping()
public bool CheckByIpAddr(String ip_addr
tr
hostadd = IPAddress.Parse(ip_addr)
catch (System.Net.Sockets.SocketException ex
last_error = ex.Message
return false
return local_ping()
private bool local_ping(
const int SEND_SIZE = 16
const int RECEIVE_SIZE = 200
const int ECHO_PORT = 7
resolved_ip_address = hostadd.ToString()
//Set up variables and String to write to the serve
byte[] SendBytes = new byte[SEND_SIZE]
byte[] RecvBytes = new byte[RECEIVE_SIZE]
// IPAddress and IPEndPoint represent the endpoint that wil
// receive the reques
// Get first IPAddress in list return by DN
int rcvd
IPEndPoint EPhost
int sent
tr
// Echo is served by port
EPhost = new IPEndPoint(hostadd, ECHO_PORT)
//Create the Socket for sending ICMP data
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)
// Send the PING to the hos
SendBytes[0] = 8
SendBytes[1] = 0
SendBytes[2] = 0xF7
SendBytes[3] = 0xFF
SendBytes[4] = 0
SendBytes[5] = 0
SendBytes[6] = 0
SendBytes[7] = 0
SendBytes[8] = 0
SendBytes[9] = 0
SendBytes[10] = 0
SendBytes[11] = 0
SendBytes[12] = 0
SendBytes[13] = 0
SendBytes[14] = 0
SendBytes[15] = 0
// send the ECH
sent = s.SendTo(SendBytes, SEND_SIZE, SocketFlags.None, EPhost)
ArrayList cr = new ArrayList()
cr.Add(s)
//now receive the ECHO respons
Socket.Select(cr, null, null, timeout_ms); //1 sec select time in microsecond
if (cr.Count > 0
rcvd = s.Receive(RecvBytes, RECEIVE_SIZE, SocketFlags.None)
last_error = ""
return true
catch (System.Net.Sockets.SocketException ex
last_error = ex.Message
return false
last_error = "Timeout trying to reach the remote host"
return false
}