Skip to content

Instantly share code, notes, and snippets.

@BranLiang
Created June 29, 2024 04:45
Show Gist options
  • Save BranLiang/e816bcda14c6c5c6098b9a60475c519d to your computer and use it in GitHub Desktop.
Save BranLiang/e816bcda14c6c5c6098b9a60475c519d to your computer and use it in GitHub Desktop.
Toggle IP address configuration between DHCP and Manual
function toggle_dhcp() {
router_address="192.168.1.105"
# Get the list of all network services
network_services=$(networksetup -listallnetworkservices | tail -n +2)
# Function to get the IP address of a network service
get_ip_address() {
networksetup -getinfo "$1" | grep "IP address: 192.168" | awk '{print $3}'
}
# Find the active network service based on IP address
active_service=""
while IFS= read -r service; do
ip_address=$(get_ip_address "$service")
if [[ -n "$ip_address" && "$ip_address" != "none" ]]; then
active_service="$service"
break
fi
done <<< "$network_services"
if [[ -z "$active_service" ]]; then
echo "No active network service found."
exit 1
fi
# Check if the active service is using DHCP or Manual
ip_assignment=$(networksetup -getinfo "$active_service" | grep -i "DHCP")
if [[ -n "$ip_assignment" ]]; then
# Switch to Manual IP configuration
sudo networksetup -setmanual "$active_service" "$(get_ip_address "$active_service")" 255.255.255.0 "$router_address"
sudo networksetup -setdnsservers "$active_service" "$router_address"
echo "Switched to Manual IP configuration for $active_service with DNS set to $router_address"
else
# Switch to DHCP
sudo networksetup -setdhcp "$active_service"
sudo networksetup -setdnsservers "$active_service" "Empty"
echo "Switched to DHCP for $active_service and DNS servers removed"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment