views:

105

answers:

3

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

+2  A: 

I think you can get what you want with 'ifconfig' command in the terminal.

Aditya R
i think it should be "ipconfig"
Ashish
Not on Linux/Unix. Only Windows decided to change the name of the command.
Douglas Leeder
and " ping " is also necessary to check whether a machine is reachable or not.
Ashish
I need to do it in C++ and determine weather the connection is up or not due to a daemon
Shahmir Javaid
I not sure but, you can write a script to check whether the network is up or not, and call this from your code
Aditya R
+3  A: 

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.

Douglas Leeder
Im already catching exceptions, And i catch a whole reem of them, But there is alot of prepocesing before i start the network. And all of the pre-processing is useless if there is no network. It would be usefull to have a check just to see if the network is up or down
Shahmir Javaid
So re-order your code - check if you can connect to (at least one) appropriate client, then do your calculations, before communicating to the connected clients.
Douglas Leeder
+3  A: 

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.

Pasi Savolainen
I have a ping function: I could use that, Thanks
Shahmir Javaid