网络通了吗? C++费多拉/Unix
是否有人有一段代码可以检查计算机上的网络是否已启用并且是否具有活动的 IP 地址。
我有一个连接到其他客户端计算机的网络软件,虽然它在计算机连接时可以工作,但如果我拔掉电缆或禁用网络,它会引发一系列异常。
如果能在上面打个勾就好了:D
提前致谢
Does any one have a snippet of their code that, checks if the network is enabled on a machine and has an active IP Address.
I have a networking software that connects to other client machines, Although it works when the machine is connected but if i unplug the cable or disable the network, It throws a whole reem of exceptions.
It would be nice to just put a check on top :D
Thanks in Advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
网络始终处于动态状态,运行开始时的简单检查不足以正确运行。
因此,不幸的是,您必须检查任何网络操作的成功状态。
至于断网状态下连程序都启动不了……考虑一下你的程序是不是在电脑死机或者断电后自动启动的。或者是否有任何其他组件遇到类似的情况或出现故障。这种情况经常发生,令人惊讶,并且仅仅因为某些 dweeb 偶然发现网络电缆而在 n+1 台计算机上重新启动程序是相当烦人的。
为了检查网络的一般可用性,您始终可以“ping -q -c 1 127.0.0.1”返回值如果 localhost 没有应答,则为 1。这应该在启动脚本中,完全没有必要在应用程序中对其进行编码。
Network is always in dynamic state, a simple check at beginning of the run is not enough for correct operation.
So unfortunately you have to check for any network operations succeess state.
As for not even starting program with network disconnected state... Consider if your program is automatically started after computer has crashed or power failure. Or if any other component has suffered something similar, or a glitch. These happen surprisingly often, and restarting program on n+1 computers just because some dweeb stumbled on network cable is quite annoying..
For checking a general availability of networking, you can always "ping -q -c 1 127.0.0.1" return value is 1 if localhost does not answer. This should be in startup script, quite unnecessary to code it in application.
您可能应该只捕获异常:否则,如果机器连接到网络,但没有连接到适当的其他机器,您就会遇到问题。
You should probably just catch the exceptions: otherwise you'll have problems if the machine is connected to a network, but not one with the appropriate other machines on it.
我认为你可以在终端中使用“ifconfig”命令得到你想要的东西。
I think you can get what you want with 'ifconfig' command in the terminal.