[转]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 ...
随机推荐
- 【分页问题】elasticsearch 深分页问题以及解决方法
本文主要参考: 1.https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html ...
- POJ 1637 Sightseeing tour(混合图欧拉回路+最大流)
http://poj.org/problem?id=1637 题意:给出n个点和m条边,这些边有些是单向边,有些是双向边,判断是否能构成欧拉回路. 思路: 构成有向图欧拉回路的要求是入度=出度,无向图 ...
- Qt5需要的_libstdc++6_4.7.2-5_???.deb
1.下载地址: http://ftp.de.debian.org/debian/pool/main/g/gcc-4.7/ 2.下载的文件: 32位:libstdc++6_4.7.2-5_i386.de ...
- GNU m4 教程[转]
原文:http://blog.csdn.net/timekeeperl/article/details/50738164 作者:garfileo 作者主页 本文整理自:https://segment ...
- Python环境管理--virtualenvwrapper
遇到问题: 当最近的开发和部署过程中,多个服务器部署的时候发现对于库和包的管理非常混乱,主要有俩个版本问题: 因为业务需要,代码得分别部署在不同的服务器上面,每次部署的时候都得重复的安装包而且不能确定 ...
- windows下的IO模型之事件选择(WSAEventSelect)模型
异步选择模型类似的是,它也允许应用程序在一个或多个套接字上,接收以事件为基础的网络事件通知.对于异步选择模型采用的网络事件来说,它们均可原封不动地移植到事件选择模型.事件选择模型和异步选择模型最主要的 ...
- ansible常用套路(一)
一.SSH互信 1 配置/etc/ansible/hosts 文件 [zabbix_agent] 172.26.4.203 172.26.4.204 172.26.4.205 [zabbix_agen ...
- 在Spring Boot中使用 @ConfigurationProperties 注解 (二十六)
@ConfigurationProperties主要作用:就是绑定application.properties中的属性 java代码 @Configuration public class DataS ...
- 免费获取一年 AVG Internet Security 2014 和 Antivirus Pro 2014
华为版的 AVG 2014 系列出炉了,用过华为版 2013 系列的童鞋都知道是什么回事,内置一年多的序列号不用那么麻烦去找了. 下载地址: 内置的许可证是:IBY9X-ESYXT-W4BZQ-QI4 ...
- SharePoint 2013的100个新功能之搜索(一)
一:新的搜索架构 SharePoint 2013中将最好的两个搜索引擎"SharePoint搜索"和"SharePoint FAST搜索服务"整合到了一个搜索引 ...