نوشته شده توسط
mtnam1372
عزیزم جواب اولت که همون مال خودمه خودمم بلد بودم مسیج باکسو بنویسم...
ایشون با این کد مشکل شما رو که گفتی:
مشکل اینجاست که اگر به اینترنت متصل نباشیم برنامه بجای اینکه کار دوم رو انجام بده دچار مشکل میشه و خاتمه پیدا میکنه
حل کردن! یعنی اگه "خودتم بلد بودی مسیج باکسو بنویسی" حتماً بلد هستی بجاش یه return true یا return false هم بذاری ....
=============
این کار هزار تا راه حل داره که یکیش پینگ کردن هست، من دو سه تاش رو میگم، با هرکدوم حال میکنی، استفاده کن، فقط استفاده از wininet.dll یکم سریعتر هست (چون مال خود مایکروسافت هست!)، اونیکی ها رو هم با عوض کردن Timeout ها میتونی سریعتر کنی (یعنی نسبت به packet lost عمومی شبکه باید تنظیم بشن)، ولی قابلیت اطمینانشون هم میاد پایین ...
یکی استفاده از WinInet هست:
//Creating the extern function...
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int Description, int ReservedValue );
//Creating a function that uses the API function...
public static bool IsConnectedToInternet( )
{
int Desc ;
return InternetGetConnectedState( out Desc, 0 ) ;
}
یکی هم استفاده از ارسال یه درخواست TCP به سایت موردنظر فرضی هست:
public static bool IsConnectedToInternet( )
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IAsyncResult result = socket.BeginConnect("www.xxxxxxxxx.com", 80, null, null );
//Set for 3 sec timeout, you can change it ...
return (result.AsyncWaitHandle.WaitOne( 3000, true ));
}
finally
{
socket.Close();
}
}
یه راهش هم استفاده از ارسال درخواست HttpWebResponse هست:
public static bool IsConnectedToInternet( )
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.xxxxxxxxx.com");
request.Timeout = 5000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return (response.StatusCode == HttpStatusCode.OK);
}
catch (Exception ex)
{
//LogError("Error: " + ex.Message);
return false;
}
}