[转]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 ...
随机推荐
- ActiveMQ(1) -- 入门案例
- 科幻小说《霜与火》 by 雷·布雷德伯里
漫漫长夜中,西姆出世了,躺在山洞冰凉的石头上,嗷嗷大哭,浑身血液奔流,脉搏每分钟一千跳.他不停地长大.妈妈用发烫的双手喂西姆吃东西.人生的梦魔开场了.一来到世间,他的眼睛就闪烁着警觉的光芒:而后又令人 ...
- 配置AD RMS的一点心得
基本上是按照下面的连接配置的,微软写的很好 AD RMS Step-by-Step Guide http://technet.microsoft.com/en-us/library/cc753531( ...
- Spring中的@Transactional
spring中的@Transactional基于动态代理的机制,提供了一种透明的事务管理机制,方便快捷解决在开发中碰到的问题. 一般使用是通过如下代码对方法或接口或类注释: @Transactiona ...
- Homebrew/Linuxbrew 安装常有工具
Homebrew https://brew.sh/ Install: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent ...
- js将 HTML 页面生成 PDF 并下载
最近碰到个需求,需要把当前页面生成 pdf,并下载.弄了几天,自己整理整理,记录下来,我觉得应该会有人需要 :) 先来科普两个插件: html2Canvas 简介 我们可以直接在浏览器端使用html2 ...
- UVA-10615 Rooks (二分图匹配)
题目大意:在一个nxn的方格中,有些位置有车,要给每一个车都涂上颜色,使得同一行和同一列的任意两个车颜色不同,求一种需要颜色种数最少的涂色方案. 题目分析:所需的最少颜色种数是显然就能得出的,假设最少 ...
- Work Queues(点对多)
Work Queues(点对多) 多个消费者在同一个消息队列中获取消息的情况.在有些应用当中,消费端接收到消息任务需要长时间的处理,如果等上一个消息处理完成以后再取下一个数据进行处理的话,势必会有一些 ...
- GVIM设置背景颜色
首先找到GVim的安装目录,在安装目录下你可以发现一个_vimrc文件,使用文本编辑器打开后在里面添加两行代码即可:代码如下set gfn=Courier_New:h14colorscheme tor ...
- windows配置Scrapy爬虫框架
一.环境 Windows10 64位 Python2.7.13 64位 下面的安装步骤最好配置代理,可能会遇到被墙的情况. 二.Python的安装 可以去参考这篇文章:http://blog.csdn ...