从C ++代码检查Internet连接 [英] Checking internet connection from C++ code

查看:101
本文介绍了从C ++代码检查Internet连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为旧版应用程序使用大型代码库时,每当我看到一段检查Internet连接是否处于活动状态的代码时,我通常都看到诸如以下功能的用法:

While working with large codebase for legacy applications, whenever I have seen a piece of code that checks whether an internet connection is active or not, I have mostly seen the uses of functions such as:

InternetCheckConnection(L"http://www.google.com",FLAG_ICC_FORCE_CONNECTION,0)
//or
BOOL bConnected = IsNetworkAlive(&dwSens)
//or
InternetGetConnectedState(&dwReturnedFlag, 0)
//or some other functions

但是有一种非常简单的方法来执行此操作,而您无需包含其他编写代码的头文件,即:

but there exists a very very simple way to do this where you wouldn't need to include other header files of write code, that is:

if (system("ping www.google.com"))

我的问题是,当我需要查看连接是否可用时,使用代码中的ping有什么弊端?

My question is that what are the drawbacks, if any, to use ping from the code when I need to see if a connection is available or not?

假定不会在要运行我的软件的计算机上禁用ping.

Assuming that ping is not going to be disabled on the machines where my software is going to run.

推荐答案

system("ping www.google.com")的缺点是双重的:

  1. 如果有人用他们自己的命令替换了系统ping命令,则可能会给您带来错误的结果[并且如果调用ping的进程正在运行时具有额外的特权,则它可能会对此产生有趣"的作用特权].这对于任何system操作都是通用的.

  1. If someone replaced the system ping command with their own, it could give you the wrong results [and if the process calling ping is running with extra privileges, it could do something "interesting" with that privilege]. This is generic for any system operation.

您正在启动另一个进程,然后必须运行该进程并关闭它,然后才能获得答案[当然,做与InternetCheckConnection差不多的事情-查找名称,将其转换为IP地址,将数据包发送到该地址,等待响应,解释该响应,依此类推].

You are starting another process, which then has to run and shut down before you get the answer [and of course do more or less the same things that InternetCheckConnection does - look up the name, translate it to an IP address, send packet to that address, wait for a response, interpret that response, and so on].

这篇关于从C ++代码检查Internet连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆