Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking internet connection with command-line PHP on linux

I'm using command-line PHP on linux to open bluetooth dialup connection, and I need a quick'n'dirty way to check if internet connection is active. Well, doesn't have to be dirty, but quick is appreciated. :) Using exec to run external commands is not a problem.

I'm thinking of pinging some stable server (e.g. google), but I'm wondering if there's some better way. Maybe checking output of ifconfig? A command that would respond with a clear response like ("cannot connect to server","connected") would naturally be best. Ideas?

like image 693
Ilari Kajaste Avatar asked Dec 19 '25 02:12

Ilari Kajaste


1 Answers

If you want something that'll work without relying on an outside server, you can check for a default route. This command will print out the number of default routes:

/sbin/route -n | grep -c '^0\.0\.0\.0'

If it's 0, you can't get to the outside world.

like image 74
caf Avatar answered Dec 20 '25 17:12

caf