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 tha开发者_C百科t 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
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.
I think you can get what you want with 'ifconfig' command in the terminal.
精彩评论