Show problems as
Classic problem #468MediumString

Validate IP Address

Real-world version: Classify a Host Address
Tracked in this browser only
Read Validate IP Address on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstRegular Expressions · Strings, animated step by step

A switch's admin console asks the operator to type a host address and has to say what kind of address it got. Given the typed text address, return "IPv4" if it is a valid version 4 address, "IPv6" if it is a valid version 6 address, and "Neither" if it is neither.

A valid IPv4 address is four decimal chunks joined by single dots. Each chunk is one to three digits long, stands for a value from 0 to 255, and carries no leading zero unless the chunk is the single digit 0. So 10.0.42.7 is valid, while 10.0.42.256, 10.0.007.7 and 10.0.42 are not.

A valid IPv6 address is eight groups joined by single colons. Each group is one to four hexadecimal digits, taken from 0-9, a-f and A-F. Leading zeros inside a group are fine and upper and lower case are both fine, but an empty group is not allowed and the shorthand that collapses a run of zero groups is not accepted by this console.

Nothing else counts: an address that is short a chunk, carries an extra separator or mixes the two forms is "Neither".

Examples

Example 1

Input
address = "10.0.42.7"
Output
"IPv4"

Four digit chunks, each between 0 and 255, none of them with a leading zero.

Example 2

Input
address = "012.4.5.6"
Output
"Neither"

The first chunk is written "012", and a chunk longer than one digit may not start with 0.

Example 3

Input
address = "abcd:1234:0000:0000:9999:aaaa:bbbb:0001"
Output
"IPv6"

Eight groups, each one to four hexadecimal digits long.

Example 4

Input
address = "1:2:3:4:5:6:7"
Output
"Neither"

Only seven groups are present, and this console does not accept a collapsed run.

Constraints

  • address consists only of English letters, digits and the characters '.' and ':'.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def valid_i_p_address(address: str) -> str:
Java
public String validIPAddress(String address)