HTTP Field Extraction with IP Address Frequency Analysis
StringsModel answerLast updated
Retrieve text fields from multiple endpoints, parse and validate IPv4 addresses, then rank them by occurrence frequency.
You are building a monitoring tool that analyzes log data distributed across multiple services. Your task is to write a script that collects data from HTTP endpoints, extracts IP addresses from the responses, and produces a frequency report.
Your script must:
-
Fetch data from a given endpoint: Make an HTTP GET request to a provided URL, including a specified header (name and value will be given), and extract the value of a designated field from the JSON response.
-
Parse and validate IP addresses: From the extracted text, identify all valid IPv4 addresses. An address is valid if it consists of exactly four decimal integers separated by dots, where each integer is between 0 and 255 inclusive, with no leading zeros (except for the standalone digit 0).
-
Process a second endpoint: Repeat the extraction for a second URL (using the same header and field name).
-
Generate a frequency report: Combine results from both sources, count how many times each distinct IP address appears, and output the addresses sorted by count in descending order. For addresses with the same count, sort them lexicographically.
Input Specification
You will be given:
- Two URLs (strings)
- A header name and value (strings)
- A field name to extract from the JSON response (string)
Output Specification
Print each distinct IP address followed by its total count, sorted by count (descending), then by address (ascending) as a tiebreaker.
Additional Requirements
- Handle HTTP errors gracefully (timeouts, non-200 status codes, malformed JSON)
- Use word boundaries when extracting IPs—don't match partial segments from longer numeric sequences
- The extracted field contains free-form text; IP addresses may appear mixed with other content
- Return addresses in the order they appear for intermediate steps (before final counting)
Example
If the first endpoint returns {"logs": "Connection from 192.168.1.1 failed, retry from 10.0.0.5"} and the second returns {"logs": "Request from 192.168.1.1 succeeded"}, your output should be:
192.168.1.1: 2
10.0.0.5: 1
Clarification Points to Confirm
- Can the specified field be missing or null?
- Should both endpoints use the same header?
- What should happen if one endpoint fails—return partial results or fail entirely?
- Are IPv6 addresses in scope, or only IPv4?
- How should sequences like
1.2.3.4.5be handled?
Hints
Hint 1
Use regular expressions with word boundaries to avoid matching IP-like substrings within longer numeric sequences
Hint 2
A dictionary or hash map is perfect for counting occurrences across multiple sources
Hint 3
Consider extracting the HTTP fetch and field extraction logic into reusable functions to avoid duplication
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem breaks down into modular steps: HTTP retrieval, text extraction, pattern matching with validation, and aggregation with sorting. A strong solution demonstrates defensive programming practices appropriate for reliability engineering work.
Step 1: HTTP Request with Header
Create a function that accepts a URL, header name, header value, and field name. The function should:
- Set a reasonable timeout (e.g., 10 seconds) to prevent indefinite hanging
- Include the custom header in the request
- Check the response status code before parsing
- Handle JSON decoding errors
- Return the field value or raise a clear exception if the field is missing
Common mistakes: Forgetting to set timeouts, not validating response status, silently swallowing errors.
Step 2: IP Address Extraction and Validation
The core challenge is distinguishing valid IPv4 addresses from near-matches. A valid address must satisfy:
- Exactly four decimal parts separated by dots
- Each part in range [0, 255]
- No leading zeros (except the single digit "0")
- Word boundaries on both sides (not embedded in longer numbers)
Use a regular expression with word boundaries: \b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b
After matching, validate each captured octet:
- Reject if it has a leading zero and length > 1 (e.g., "010")
- Reject if the numeric value exceeds 255
Edge cases to test:
256.1.1.1— invalid (256 > 255)192.168.01.1— invalid (leading zero)0.0.0.0— valid1.2.3.4.5— the regex with word boundaries should not match this as an IPtest192.168.1.1more— without word boundaries, this would incorrectly match
Return a list of all valid addresses in the order they appear, preserving duplicates since we need them for counting.
Step 3: Reusable Extraction
Rather than duplicating code for the second URL, parameterize the fetch-and-extract logic. A function that takes (URL, header_name, header_value, field_name) and returns a list of IPs serves both endpoints.
When one endpoint fails, decide on a strategy:
- Fail fast: If any endpoint is unreachable, abort and report the error
- Partial results: Collect IPs from successful endpoints only and note which failed
For a monitoring tool, failing fast is often safer—partial data might hide outages. Clarify this with your interviewer.
Step 4: Aggregation and Sorting
Use a dictionary to count occurrences across both sources:
from collections import Counter
ip_counts = Counter(ips_from_url1 + ips_from_url2)
Sort by count descending, with lexicographic order as a tiebreaker:
sorted_ips = sorted(ip_counts.items(), key=lambda x: (-x[1], x[0]))
The negative count ensures descending order, while the address string provides a stable tiebreaker.
Implementation (Python)
import re
import requests
from collections import Counter
def fetch_field(url, header_name, header_value, field_name, timeout=10):
"""Fetch JSON from URL and extract a specific field."""
headers = {header_name: header_value}
try:
response = requests.get(url, headers=headers, timeout=timeout)
response.raise_for_status()
data = response.json()
if field_name not in data:
raise ValueError(f"Field '{field_name}' not found in response")
return data[field_name]
except requests.RequestException as e:
raise RuntimeError(f"HTTP request failed for {url}: {e}")
except ValueError as e:
raise RuntimeError(f"JSON parsing failed for {url}: {e}")
def extract_ips(text):
"""Extract all valid IPv4 addresses from text."""
pattern = r'\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b'
matches = re.findall(pattern, text)
valid_ips = []
for match in matches:
# Check each octet
if all(is_valid_octet(octet) for octet in match):
valid_ips.append('.'.join(match))
return valid_ips
def is_valid_octet(octet_str):
"""Validate a single octet: no leading zeros, value <= 255."""
if len(octet_str) > 1 and octet_str[0] == '0':
return False
return 0 <= int(octet_str) <= 255
def count_and_sort_ips(ip_list):
"""Count IPs and return sorted by frequency (desc) then lexicographically."""
counts = Counter(ip_list)
return sorted(counts.items(), key=lambda x: (-x[1], x[0]))
def main(url1, url2, header_name, header_value, field_name):
# Fetch from both endpoints
text1 = fetch_field(url1, header_name, header_value, field_name)
text2 = fetch_field(url2, header_name, header_value, field_name)
# Extract IPs
ips1 = extract_ips(text1)
ips2 = extract_ips(text2)
# Count and sort
all_ips = ips1 + ips2
ranked = count_and_sort_ips(all_ips)
# Output
for ip, count in ranked:
print(f"{ip}: {count}")
# Example usage
# main("https://api.example.com/logs1", "https://api.example.com/logs2",
# "Authorization", "Bearer token123", "logs")
Complexity Analysis
- Time: O(n + m log m) where n is the total length of text from both endpoints and m is the number of distinct IPs. Regex scanning is O(n), sorting is O(m log m).
- Space: O(m) for the counter and sorted list.
For typical log analysis with hundreds of IPs in kilobytes of text, this is efficient. Network I/O dominates runtime.
Trade-offs and Production Considerations
Error handling strategy: The implementation fails fast if either endpoint is unreachable. Alternatively, you could collect partial results and log warnings. The right choice depends on whether incomplete data is worse than no data.
Regex versus manual parsing: Regex is concise but harder to debug. Manual state-machine parsing gives more control over edge cases but adds complexity. For this problem, regex with post-validation strikes a good balance.
IPv6 support: The current solution handles only IPv4. Adding IPv6 would require a separate regex pattern and validation logic for hexadecimal segments and compression rules.
Concurrency: Fetching endpoints sequentially is simple but slow. For many URLs, use asyncio or threading to parallelize requests.
Testing boundaries: Unit tests should cover 255.255.255.255, 0.0.0.0, 192.168.001.1 (invalid), 1.2.3.4.5 (should not match), and text without any IPs.