[转]C# 测试网络连接
原文链接: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# 测试网络连接的更多相关文章
- Android检查设备是否可以访问互联网,判断Internet连接,测试网络请求,解析域名
安卓SDK提供了ConnectivityManager类,那么我们就可以轻松的获取设备的网络状态以及联网方式等信息. 但是要想知道安卓设备连接的网络能不能访问到Internet,就要费一番周折了. 本 ...
- 虚拟机linux系统网络连接配置问题总结
1.虚拟机与CentOS的安装与配置参考本人博客:https://www.cnblogs.com/ClikeL/p/11743520.html 2.测试网络连接 ping www.baidu.com ...
- Android测试网络是否连接
一.布局页面 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns ...
- ios 测试网络是否连接
转自:http://blog.csdn.net/lwq421336220/article/details/16982857 - (BOOL) connectedToNetwork { //创建零地址, ...
- VMware的三种网络连接方式区别
关于VMware的三种网络连接方式,NAT,Bridged,Host-Only ,在刚接触的时候通常会遇到主机Ping不通虚拟机而虚拟机能Ping得通主机:主机与虚拟机互不相通等等网络问题.本文就这三 ...
- 【虚拟机】在VMware中安装Server2008之后配置网络连接的几种方式
VMware虚拟机的网络连接方式分为三种:桥接模式.NAT模式.仅主机(Host Only) (1)桥接模式 桥接模式即在虚拟机中虚拟一块网卡,这样主机和虚拟机在一个网段中就被看作是两个独立的IP地址 ...
- Android网络连接判断与处理
博客分类: Android 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="android ...
- [转]VMware Workstation网络连接的三种模式
经常要使用VMWare Workstation来在本地测试不同的操作系统,以前也搞不清楚网络连接三种模式,最近看了几篇文章才算明白.现总结如下: 1. VMware Workstation的虚拟网络组 ...
- Android 网络连接判断与处理
Android网络连接判断与处理 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="and ...
随机推荐
- 记我一年的OI之路
upd:感觉没必要设密码了吧,把这个发出来还能显得自己弱颓一些.. 自从我刚刚接触c++,到现在已经快一年了吧,这一年中,我学到了很多,失去了很多,也得到了很多. 开通了blog,那就从现在,就是一个 ...
- 带宽检测工具iftop
1.安装 # yum install iftop –y 2.使用 # iftop -i eth0 -n # iftop -i eth0 -P 说明: 中间的<= =>这两个左右箭头,表示的 ...
- mysql导入source数据库
首先要确保数据库存在,如果不存在则创建 方法1 source 很智能,很方便,很快捷. # mysql -uroot -p Enter password: Welcome to the MySQL m ...
- Mediator(中介者)
意图: 用一个中介对象来封装一系列的对象交互.中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互. 适用性: 一组对象以定义良好但是复杂的方式进行通信.产生的相互依 ...
- mysql获取随机数据的方法
order by rand() 数据多了极慢,随机性非常好,适合非常小数据量的情况. 复制代码 代码如下: SELECT * FROM table_name AS r1 JOIN (SELECT (R ...
- JQuery中width和JS中JS中关于clientWidth offsetWidth scrollWidth 等的含义
JQuery中: width()方法用于获得元素宽度: innerWidth()方法用于获得包括内边界(padding)的元素宽度: outerWidth()方法用于获得包括内边界(padding)和 ...
- mac上将代码上传到github以及github对100M以上文件限制上传的处理(lfs)。
前言 有时我们会写一些小程序来学习新的知识,但是完事之后过一段时间可能会忘记,最好的办法就是找到原来的代码看一看.现在可以将代码免费托管到一些网站上,其中最著名的非github莫属了, 今天就把这个过 ...
- vnc viewer 点击system 卡死现象
转自:http://zhangjunli177.blog.163.com/blog/static/1386073082012103052527557/ VNC viewer desktop dead ...
- 表统计信息(storge)相关
select t1.NUM_ROWS,t1.BLOCKS,t1.EMPTY_BLOCKS,t1.AVG_SPACE,t1.CHAIN_CNT,t1.AVG_ROW_LEN from user_tab_ ...
- Android将图片保存到相册并及时看到
Android中将图片保存到SD卡中,相册里不会及时出现这张图片,因为没有及时更新其索引,一般需要开机几次.当然我们可以手动更新其索引. 1,首先将文件保存到SD卡中. String filePath ...