wmdeit-cf-wmdelib/scripts/getipv4.sh

59 lines
1.4 KiB
Bash

#!/bin/sh
#!/bin/sh
# Define a function to get the first IPv4 address of a FreeBSD interface
get_ipv4address_freebsd() {
local interface="$1"
# Use ifconfig to get IPv4 addresses of the specified interface
ipv4_addresses=$(ifconfig "$interface" | awk '/inet / {print $2}')
# Extract the first IPv4 address
first_ipv4_address=""
for addr in $ipv4_addresses; do
first_ipv4_address="$addr"
break # Exit after getting the first IPv4 address
done
# Return the first IPv4 address
echo -n "$first_ipv4_address"
}
get_ipv4address_linux() {
# Set the interface name you want to query
local interface="$1" # Replace with your desired interface
# Use ip command to get IPv4 addresses of the specified interface
ipv4_addresses=$(ip -4 addr show dev "$interface" | grep -oP 'inet \K[\d.]+')
# Extract the first IPv4 address
first_ipv4_address=""
for addr in $ipv4_addresses; do
first_ipv4_address="$addr"
break # Exit after getting the first IPv4 address
done
# Check if an address was found
if [ -n "$first_ipv4_address" ]; then
echo -n "$first_ipv4_address"
else
exit 1;
fi
}
kernel_name=$(uname -s)
interface="$1" # Replace with your desired interface
if [ "$kernel_name" = "FreeBSD" ]; then
result=$(get_ipv4address_freebsd "$interface")
else
result=$(get_ipv4address_linux "$interface")
fi
echo -n "$result"