There is a way to check internet connection with simplest and minimal action from software, not even ping needed.
Common way would be to use system() call and ping inside and parse output. But there is even a simpler and lighter way to do so.
Not even sending ICMP packet needed.
We create socket:
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = { AF_INET, htons(443), inet_addr("8.8.8.8") };
We will check via connecting to google DNS (which is available 24/7) and using port 443 for common HTTPS – always open.
//setting timeout 1 second
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
We set timeout to 1 second – it should be enough, also could be reduced in case of need.
Then we use
connect(sockfd, (struct sockaddr *) &addr, sizeof(addr))
If connect() returns 0 – there is connection, if -1 there is no.
Then we close socket.