原文链接:http://blog.csdn.net/lsfa1234/article/details/6291228

using System;
using System.Web;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading; namespace VvxT.Web
{
public class Internet
{
#region 利用API方式获取网络链接状态
private static int NETWORK_ALIVE_LAN = 0x00000001;
private static int NETWORK_ALIVE_WAN = 0x00000002;
private static int NETWORK_ALIVE_AOL = 0x00000004; [DllImport("sensapi.dll")]
private extern static bool IsNetworkAlive(ref int flags);
[DllImport("sensapi.dll")]
private extern static bool IsDestinationReachable(string dest, IntPtr ptr); [DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue); public Internet() { } public static bool IsConnected()
{
int desc = ;
bool state = InternetGetConnectedState(out desc, );
return state;
} public static bool IsLanAlive()
{
return IsNetworkAlive(ref NETWORK_ALIVE_LAN);
}
public static bool IsWanAlive()
{
return IsNetworkAlive(ref NETWORK_ALIVE_WAN);
}
public static bool IsAOLAlive()
{
return IsNetworkAlive(ref NETWORK_ALIVE_AOL);
}
public static bool IsDestinationAlive(string Destination)
{
return (IsDestinationReachable(Destination, IntPtr.Zero));
}
#endregion /// <summary>
/// 在指定时间内尝试连接指定主机上的指定端口。 (默认端口:80,默认链接超时:5000毫秒)
/// </summary>
/// <param name="HostNameOrIp">主机名称或者IP地址</param>
/// <param name="port">端口</param>
/// <param name="timeOut">超时时间</param>
/// <returns>返回布尔类型</returns>
public static bool IsHostAlive(string HostNameOrIp, int? port, int? timeOut)
{
TcpClient tc = new TcpClient();
tc.SendTimeout = timeOut ?? ;
tc.ReceiveTimeout = timeOut ?? ; bool isAlive;
try
{
tc.Connect(HostNameOrIp, port ?? );
isAlive = true;
}
catch
{
isAlive = false;
}
finally
{
tc.Close();
}
return isAlive;
} } public class TcpClientConnector
{
/// <summary>
/// 在指定时间内尝试连接指定主机上的指定端口。 (默认端口:80,默认链接超时:5000毫秒)
/// </summary>
/// <param name= "hostname ">要连接到的远程主机的 DNS 名。</param>
/// <param name= "port ">要连接到的远程主机的端口号。 </param>
/// <param name= "millisecondsTimeout ">要等待的毫秒数,或 -1 表示无限期等待。</param>
/// <returns>已连接的一个 TcpClient 实例。</returns>
public static TcpClient Connect(string hostname, int? port, int? millisecondsTimeout)
{
ConnectorState cs = new ConnectorState();
cs.Hostname = hostname;
cs.Port = port ?? ;
ThreadPool.QueueUserWorkItem(new WaitCallback(ConnectThreaded), cs);
if (cs.Completed.WaitOne(millisecondsTimeout ?? , false))
{
if (cs.TcpClient != null) return cs.TcpClient;
return null;
//throw cs.Exception;
}
else
{
cs.Abort();
return null;
//throw new SocketException(11001); // cannot connect
}
} private static void ConnectThreaded(object state)
{
ConnectorState cs = (ConnectorState)state;
cs.Thread = Thread.CurrentThread;
try
{
TcpClient tc = new TcpClient(cs.Hostname, cs.Port);
if (cs.Aborted)
{
try { tc.GetStream().Close(); }
catch { }
try { tc.Close(); }
catch { }
}
else
{
cs.TcpClient = tc;
cs.Completed.Set();
}
}
catch (Exception e)
{
cs.Exception = e;
cs.Completed.Set();
}
} private class ConnectorState
{
public string Hostname;
public int Port;
public volatile Thread Thread;
public readonly ManualResetEvent Completed = new ManualResetEvent(false);
public volatile TcpClient TcpClient;
public volatile Exception Exception;
public volatile bool Aborted;
public void Abort()
{
if (Aborted != true)
{
Aborted = true;
try { Thread.Abort(); }
catch { }
}
}
}
}
}

类代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Sockets; namespace VvxT.Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bool IsConnected = Internet.IsConnected();
bool IsAOLAlive = Internet.IsAOLAlive(); DateTime oldTime1 = DateTime.Now;
bool IsDestinationAlive = Internet.IsDestinationAlive("cn.yahoo.com");
DateTime newTime1 = DateTime.Now;
TimeSpan ts1 = newTime1 - oldTime1; bool IsLanAlive = Internet.IsLanAlive();
bool IsWanAlive = Internet.IsWanAlive(); DateTime oldTime2 = DateTime.Now;
//bool IsHostAlive = Internet.IsHostAlive("hk.yahoo.com", null, null);//不推荐使用(无法实际控制超时时间)
bool IsHostAlive;
TcpClient tc = TcpClientConnector.Connect("hk.yahoo.com", null, null);//推荐使用(采用线程池强行中断超时时间)
try
{
if (tc != null)
{
tc.GetStream().Close();
tc.Close();
IsHostAlive = true;
}
else
IsHostAlive = false;
}
catch { IsHostAlive = false; }
DateTime newTime2 = DateTime.Now;
TimeSpan ts2 = newTime2 - oldTime2; Response.Write("Connect:" IsConnected "<br />");
Response.Write("Lan:" IsLanAlive "<br />");
Response.Write("Wan:" IsWanAlive "<br />");
Response.Write("Aol:" IsAOLAlive "<br />");
Response.Write("Sip(cn.yahoo.com):" IsDestinationAlive " 耗时:" ts1.TotalMilliseconds "<br />");
Response.Write("TcpClient(hk.yahoo.com):" IsHostAlive " 耗时:" ts2.TotalMilliseconds "<br />"); }
}
}

使用示例

Connect:True
Lan:True
Wan:True
Aol:True
Sip(cn.yahoo.com):True 耗时:265.625
TcpClient(hk.yahoo.com):False 耗时:

最后效果

[转]C# 测试网络连接的更多相关文章

  1. Android检查设备是否可以访问互联网,判断Internet连接,测试网络请求,解析域名

    安卓SDK提供了ConnectivityManager类,那么我们就可以轻松的获取设备的网络状态以及联网方式等信息. 但是要想知道安卓设备连接的网络能不能访问到Internet,就要费一番周折了. 本 ...

  2. 虚拟机linux系统网络连接配置问题总结

    1.虚拟机与CentOS的安装与配置参考本人博客:https://www.cnblogs.com/ClikeL/p/11743520.html 2.测试网络连接 ping www.baidu.com ...

  3. Android测试网络是否连接

    一.布局页面 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns ...

  4. ios 测试网络是否连接

    转自:http://blog.csdn.net/lwq421336220/article/details/16982857 - (BOOL) connectedToNetwork { //创建零地址, ...

  5. VMware的三种网络连接方式区别

    关于VMware的三种网络连接方式,NAT,Bridged,Host-Only ,在刚接触的时候通常会遇到主机Ping不通虚拟机而虚拟机能Ping得通主机:主机与虚拟机互不相通等等网络问题.本文就这三 ...

  6. 【虚拟机】在VMware中安装Server2008之后配置网络连接的几种方式

    VMware虚拟机的网络连接方式分为三种:桥接模式.NAT模式.仅主机(Host Only) (1)桥接模式 桥接模式即在虚拟机中虚拟一块网卡,这样主机和虚拟机在一个网段中就被看作是两个独立的IP地址 ...

  7. Android网络连接判断与处理

    博客分类: Android 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="android ...

  8. [转]VMware Workstation网络连接的三种模式

    经常要使用VMWare Workstation来在本地测试不同的操作系统,以前也搞不清楚网络连接三种模式,最近看了几篇文章才算明白.现总结如下: 1. VMware Workstation的虚拟网络组 ...

  9. Android 网络连接判断与处理

    Android网络连接判断与处理  获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="and ...

随机推荐

  1. mac上 sublime的配置,支持c++11且支持输入

    首先下载mac版本的 sublimetext3 下载链接: https://www.sublimetext.com/3 接着可以按照其他博客的方法来安装一些插件,便于我们的工作和学习 安装sublim ...

  2. IDEA 搭建授权服务器

    引用地址  http://blog.lanyus.com/archives/317.html 今天突出发现基本公开的激活地址都被屏蔽了(IDEA 2017.3 版本) 记录一下 docker pull ...

  3. python 计算字典value值的和

    my_dict = {,,} print(sum(my_dict.values()))

  4. Looper.loop() android线程中的消息循环

    Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Loope ...

  5. Codeforces 909C Python Indentation:树状数组优化dp

    题目链接:http://codeforces.com/contest/909/problem/C 题意: Python是没有大括号来标明语句块的,而是用严格的缩进来体现. 现在有一种简化版的Pytho ...

  6. 雷林鹏分享:Ruby 范围(Range)

    Ruby 范围(Range) 范围(Range)无处不在:January 到 December. 0 到 9.等等.Ruby 支持范围,并允许我们以不同的方式使用范围: 作为序列的范围 作为条件的范围 ...

  7. Hive之基本操作

    1,CREATE table. CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name [(col_name data_type [COMMENT col ...

  8. C# Lock关键字

    lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁. lock语句根本使用的就是Monitor.Enter和Monitor.Exit,也就是说lock(this) ...

  9. poj1191 棋盘分割。 dp

    连接:http://poj.org/problem?id=1191 思路:额,其实就是直接搞记录一下就可以了. #include <stdio.h> #include <string ...

  10. 剑指offer+名企面试官精讲典型编程题,28题扩展题

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...