Skip to content

Instantly share code, notes, and snippets.

@brycepg
Last active July 10, 2021 01:26
Show Gist options
  • Save brycepg/ba117a37de53906dc8fcc312bd7d5fee to your computer and use it in GitHub Desktop.
Save brycepg/ba117a37de53906dc8fcc312bd7d5fee to your computer and use it in GitHub Desktop.
Get IP Address from hostname bash function
# Get IP address from hostname using Python
# Args:
# $1 - hostname
# Returns:
# The ip address
ipfromhostname() {
local hostname="$1"
if [ -z "$hostname" ]; then
>&2 echo 'Must supply hostname as an argument'
return 1
fi
local python_exists=$(type python 2>/dev/null)
if [ -z "$python_exists" ]; then
>&2 echo Requires python
return 1
fi
python -c "import socket; print(socket.gethostbyname(\"$hostname\"))" 2>/dev/null
local ret="$?"
if [[ "$ret" != 0 ]]; then
>&2 echo Hostname not found
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment