Given a table logs containing server access log information, write a SQL solution to find invalid IP addresses.
An IPv4 address is considered invalid if it meets any of these conditions:
- Contains numbers greater than 255 in any octet
- Has leading zeros in any octet (like 01.02.03.04)
- Has less or more than 4 octets
Return the result table with columns ip and invalid_count ordered by invalid_count and ip in descending order respectively.
Table Schema
| Column Name | Type | Description |
|---|---|---|
log_id
PK
|
int | Unique identifier for each log entry |
ip
|
varchar | IP address from server access logs |
status_code
|
int | HTTP status code for the request |
Input & Output
| log_id | ip | status_code |
|---|---|---|
| 1 | 192.168.1.1 | 200 |
| 2 | 192.168.01.1 | 200 |
| 3 | 256.1.1.1 | 404 |
| 4 | 192.168.01.1 | 500 |
| 5 | 10.0.0 | 200 |
| ip | invalid_count |
|---|---|
| 192.168.01.1 | 2 |
| 256.1.1.1 | 1 |
| 10.0.0 | 1 |
192.168.01.1 appears twice and is invalid due to leading zero in third octet. 256.1.1.1 is invalid because 256 > 255. 10.0.0 is invalid because it has only 3 octets instead of 4. 192.168.1.1 is valid so not included in output.
| log_id | ip | status_code |
|---|---|---|
| 1 | 192.168.1.1 | 200 |
| 2 | 10.0.0.1 | 404 |
| 3 | 127.0.0.1 | 200 |
| ip | invalid_count |
|---|
All IP addresses are valid (proper format, no leading zeros, all octets ≤ 255, exactly 4 octets), so the result is empty.
| log_id | ip | status_code |
|---|---|---|
| 1 | 0.0.0.0 | 200 |
| 2 | 00.0.0.0 | 404 |
| 3 | 255.255.255.255 | 200 |
| 4 | 1.2.3.4.5 | 500 |
| ip | invalid_count |
|---|---|
| 1.2.3.4.5 | 1 |
| 00.0.0.0 | 1 |
0.0.0.0 and 255.255.255.255 are valid edge cases. 00.0.0.0 is invalid due to leading zero. 1.2.3.4.5 is invalid due to having 5 octets instead of 4.
Constraints
-
1 ≤ log_id ≤ 10000 -
ipcontains only digits, dots, and may have invalid formats -
200 ≤ status_code ≤ 599