0

I'm trying to write a script that takes a machine name as a command line argument and displays a message informing me whether the host is on the local network.

Here's what I have:

#!/bin/bash
gateway=$(ip route | grep default | cut -d' ' -f3)

if [[ $(ip route get "$1" | grep -q $gateway) ]]; then

echo "$1 is on the local network"

else

echo "$1 is not on the local network"

fi 

Whenever I run it with my machine name (ubuntu) I get the following output:

Error: any valid prefix is expected rather than "ubuntu".
ubuntu is not on the local network

I'm not sure what the error means and why I'm getting it, as well as if the script is even doing what it should be doing. Any advice would be appreciated. Thanks!

1
  • 3
    ip route get expects an IP prefix (e.g., ip route get 192.168), not a hostname. Convert the hostname to an IP, maybe.
    – muru
    Commented Mar 5, 2020 at 2:49

2 Answers 2

2

On my Ubuntu linux the IP address is in the 4th field. Ensure the cut delimiter is getting what you think

ip r | grep default && ip r | grep default | cut -d' ' -f3 && ip r | grep default | cut -d' ' -f4
none default via 192.168.1.1 dev eth1  proto none  metric 0
via
192.168.1.1
0

To check if the machine is on the same (sub)network, you have to see if it's address is in the range of the address mask... ip addr shows it in the brd field.

Another, sneakier, way is to see what e.g. traceroute says.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.