Search code examples
network-programmingluaneovim

Get network connection status in neovim


Because of my work environment I'm actually working offline quite a bit, and I have some lsp configurations that I'm trying to toggle automatically based on my current network status. Is there a way to get the current network status in lua, without needing to echo a shell command and try to parse the stdout?


Solution

  • You could check your network status with ping to a known host (for example Google DNS server 8.8.8.8) and use return code: 0 if host is alive (network ON), !=0 if host down (network OFF).

    -- ping to host 8.8.8.8 without output
    local ret = os.execute("ping -c 3 8.8.8.8 > /dev/null 2>&1")
    
    if ret == 0 then
      print("Network ON")
    else
      print("Network OFF")
    end