使用API判断网络是否连通 InternetGetConnectedState / IsNetworkAlive

这篇博客介绍了如何使用Windows API函数`InternetGetConnectedState()`和`IsNetworkAlive()`来检测网络连接状态。`InternetGetConnectedState()`可能无法及时反映网络变化,而`IsNetworkAlive()`能及时反应但依赖System Event Notification服务。文章还提供了简单的C++示例代码,并提及了老师的AI教程资源。
摘要由CSDN通过智能技术生成
               

// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "test.h"
#include <Wininet.h>
#include <Sensapi.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/
// The one and only application object

CWinApp theApp;

using namespace std;

void Fun_InternetGetConnectedState()
{
  
//#define INTERNET_CONNECTION_MODEM           1
//#define INTERNET_CONNECTION_LAN             2
//#define INTERNET_CONNECTION_PROXY           4
//#define INTERNET_CONNECTION_MODEM_BUSY      8
  
DWORD   flags;//上网方式
BOOL   m_bOnline=TRUE;//是否在线  

m_bOnline=InternetGetConnectedState(&flags,0);  
if(m_bOnline)//在线  

在Linux中,可以使用socket编程来检测网络连接状态。具体来说,可以使用以下步骤: 1. 创建一个socket对象,使用AF_INET和SOCK_DGRAM参数来创建UDP socket。 2. 绑定socket到一个本地地址和端口。 3. 使用connect()函数将socket连接到一个远程地址和端口。可以使用google.com的IP地址和80端口来测试连接。 4. 调用select()函数来等待连接的结果。如果连接成功,select()函数将返回1,否则将返回0或-1。 下面是一个简单的示例代码,可以检测网络连接状态: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/select.h> #include <errno.h> int check_network_connection() { int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if(sockfd < 0){ perror("socket"); return -1; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = inet_addr("74.125.24.106"); //google.com if(connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0){ if(errno != EINPROGRESS){ perror("connect"); close(sockfd); return -1; } } fd_set rset, wset; FD_ZERO(&rset); FD_SET(sockfd, &rset); wset = rset; struct timeval tv; tv.tv_sec = 5; //设置超时时间为5秒 tv.tv_usec = 0; int ret = select(sockfd + 1, &rset, &wset, NULL, &tv); if(ret < 0){ perror("select"); close(sockfd); return -1; } else if(ret == 0){ printf("timeout\n"); close(sockfd); return 0; } else{ if(FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)){ printf("network connected\n"); close(sockfd); return 1; } else{ printf("select error\n"); close(sockfd); return -1; } } } int main() { int ret = check_network_connection(); if(ret == 1){ printf("network connected\n"); } else{ printf("network disconnected\n"); } return 0; } ``` 这个示例代码中,check_network_connection()函数返回1表示网络连接正常,返回0表示网络连接不正常,返回-1表示发生错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值