Write a method that determines whether a given string is a valid IPv4 address.
A valid IPv4 address must meet all of the following criteria:
- Contains exactly 4 parts separated by dots
- Each part must be a whole number between 0 and 255 (inclusive)
- No leading zeros are allowed (the string "01" is invalid, but "0" alone is valid)
- Null or empty input is considered invalid
Examples
Input: ip = "192.168.1.1"
Output: true
Explanation: All 4 parts are valid numbers between 0 and 255
Input: ip = "256.0.0.1"
Output: false
Explanation: 256 exceeds the maximum value of 255
Input: ip = "01.1.1.1"
Output: false
Explanation: Leading zeros are not permitted in IP address octets
Input: ip = "1.2.3"
Output: false
Explanation: Only 3 parts found, a valid IPv4 address requires exactly 4
Input: ip = null
Output: false
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 All Time Leaderboard
Contest runs January 1, 1970 - December 31, 9999. Complete challenges to climb the leaderboard!
Points are calculated for challenges completed during the contest period.