您的位置:首页 > 理论基础 > 计算机网络

判断网络状态

2014-01-09 10:08 190 查看
C++实现

// GetInternetConnState.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include < Wininet.h>
#pragma  comment(lib, "Wininet.lib")
int main()
{
DWORD   flags;//上网方式
BOOL   m_bOnline;//是否在线

m_bOnline = InternetGetConnectedState(&flags, 0);

if (m_bOnline)//在线
{
int b;
if (flags& INTERNET_CONNECTION_MODEM)
{
b = flags& INTERNET_CONNECTION_MODEM;
}
else if (flags&INTERNET_CONNECTION_LAN)
{
b = flags&INTERNET_CONNECTION_LAN;
}
else if (flags& INTERNET_CONNECTION_PROXY)
{
b = flags& INTERNET_CONNECTION_PROXY;
}
switch (b)
{
case   INTERNET_CONNECTION_MODEM:
printf("在线:拨号上网\n");
break;
case   INTERNET_CONNECTION_LAN:
printf("在线:通过局域网\n");
break;
case   INTERNET_CONNECTION_PROXY:
printf("在线:代理\n");
break;
}
if (flags&INTERNET_CONNECTION_MODEM_BUSY == INTERNET_CONNECTION_MODEM_BUSY)
printf("MODEM被其他非INTERNET连接占用\n");
}
else
printf("不在线\n");
return 0;
}


C#实现

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using System.Runtime.InteropServices;

namespace GetInternetConnStateCS
{
public partial class Form1 : Form
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
public Form1()
{
InitializeComponent();
}
private bool IsConnected()
{

int I = 0;

bool state = InternetGetConnectedState(out I, 0);

return state;

}

private void button1_Click(object sender, EventArgs e)
{
//while (true)
//{
if (IsConnected())
{
label1.Text = "状态:网络畅通!";
}
else
{
label1.Text = "状态:与目标网络无连接!";
}
//    System.Threading.Thread.Sleep(1000);
//}
}

private void Form1_Load(object sender, EventArgs e)
{

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: