Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Validate IPv4 and IPv6 Address

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Validate IPv4 and IPv6 Address. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

At Meta, systems such as network-facing services and internal traffic filters need strict IP parsing. Implement a function that takes a string and returns whether it is a valid IPv4 address, valid IPv6 address, or Neither.

Formal Specification

Write a function validate_ip(address) that accepts a string address and returns one of:

  • "IPv4" if the string is a valid IPv4 address
  • "IPv6" if the string is a valid IPv6 address
  • "Neither" otherwise

A valid IPv4 address has exactly 4 decimal parts separated by .. Each part must contain only digits, be in the range 0 to 255, and must not contain leading zeros unless the part is exactly "0".

A valid IPv6 address has exactly 8 parts separated by :. Each part must be 1 to 4 characters long and contain only hexadecimal characters: 0-9, a-f, or A-F.

Constraints

  • 1 <= len(address) <= 100
  • IPv4 validation requires exactly 4 segments separated by '.'
  • Each IPv4 segment must be a decimal number in [0, 255] with no leading zeros unless the segment is exactly '0'
  • IPv6 validation requires exactly 8 groups separated by ':'
  • Each IPv6 group must contain 1 to 4 hexadecimal characters
  • Do not use built-in IP parsing libraries

Function Signature

def validate_ip(address):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output