判断网络是否通

在Ubuntu 20中,可以使用C++编写程序来判断当前网络是否通畅。一种常用的方法是尝试访问一个可靠的远程服务器,并检查是否能够成功建立连接。在C++中,可以使用sockets库进行网络连接测试。

以下是一个简单的C++程序,用于检查网络连接状态:

#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

bool isNetworkConnected() {
    
    
    // 创建一个套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
    
    
        std::cerr << "Error creating socket." << std::endl;
        return false;
    }

    // 设置服务器信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(80); // HTTP默认端口
    inet_pton(AF_INET, "8.8.8.8", &server.sin_addr); // 使用Google的公共DNS服务器

    // 尝试连接
    int result = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    close(sockfd);

    if (result == 0) {
    
    
        return true; // 连接成功,网络通畅
    } else {
    
    
        return false; // 连接失败,网络不通
    }
}

int main() {
    
    
    if (isNetworkConnected()) {
    
    
        std::cout << "网络通畅。" << std::endl;
    } else {
    
    
        std::cout << "网络不通。" << std::endl;
    }

    return 0;
}

gethostbyname()函数可以判断网络是否同,如果不同,会快速返回,不会卡住。

#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

string url = "www.baidu.com";
string Curl::getIP()
{
    
    
    
    if(IP_ != "") return IP_;
    struct hostent* host = NULL;
    host = gethostbyname(url.c_str());
    // host = gethostbyname("120.25.130.188");
    if(host == NULL)
    {
    
    
        return IP_;//""
    }
    char* ip_ = NULL;
    ip_ = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);
    if(ip_)
    {
    
    
        IP_ = ip_;
        return IP_;
    }
    else return IP_;//""
    
}

猜你喜欢

转载自blog.csdn.net/weixin_43466192/article/details/132039377
今日推荐