判断是否联网

1、

try
{
System.Net.IPHostEntry ip 
= System.Net.Dns.GetHostByName("www.csdn.net");
}

catch(Exception ex)
{
//联不上网
}

2、
准确的说,是判断能否和某台主机用某种协议相连接

using System.Net.Sockets;

try
{
    Socket soc 
= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    soc.Connect(
"xxx.163.com"80);
    Console.WriteLine(
"Success");
}

catch (SocketException se)
{
    Console.WriteLine(se.Message);
}

3、

/// <summary>
 
/// WinInet 的摘要说明。
 
/// </summary>

 public class WinInet
 
{
  
private const int INTERNET_CONNECTION_MODEM = 1;
  
private const int INTERNET_CONNECTION_LAN = 2;
  [DllImport(
"winInet.dll")]
  
private static extern bool InternetGetConnectedState(
   
ref int dwFlag,
   
int dwReserved
   );

  
/// <summary>
  
/// 是否连接在Internet
  
/// </summary>
  
/// <param name="IsModem">如果连接在Internet,判断是否通过Modem上网</param>
  
/// <returns></returns>

  public static bool IsOnline(out bool IsModem)
  
{
   IsModem
=false;
   
int dwFlag = new int();
   
if(!InternetGetConnectedState(ref dwFlag, 0))    
    
return false;
   
else if((dwFlag & INTERNET_CONNECTION_MODEM)!=0)
    IsModem
=true;
   
else if((dwFlag & INTERNET_CONNECTION_LAN)!=0)
    IsModem
=false;
   
return true;
  }

 }
posted on 2005-12-14 09:04  冷月孤峰  阅读(337)  评论(0)    收藏  举报