Extract IP Address from File using Python (original) (raw)
Last Updated : 19 Jan, 2026
An IPv4 address is a 32‑bit numerical label used to identify a device on a network. It is written as four decimal numbers (each between 0 and 255) separated by periods (dots). Example of IPs: 192.168.1.1 , 8.8.8.8 , 127.0.0.1
Below are Python examples that demonstrate how to extract all IPs and only valid IPv4 addresses from a file using regular expressions.
This method extracts any IP-like pattern, even if it is not valid (e.g., 999.999.999.999). Below is the sample file (test.txt) used in this example:

test.txt
Python `
import re
with open('test.txt', 'r') as fh: lines = fh.readlines() pattern = re.compile(r'(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})')
ip_list = [] for line in lines: match = pattern.search(line) if match: ip_list.append(match.group()) print(ip_list)
`
**Output
['192.168.4.164', '69.168.4.226', '32.89.31.14', '67.168.3.227']
**Explanation:
- **pattern = re.compile(...): Define pattern to match IPv4 addresses.
- **ip_list = []: Initialize list for IPs.
- **for line in lines... Loop lines, search IPs, append matches.
To extract only valid IPv4 addresses (0-255), we need a stricter regex pattern. Rules for a Valid IPv4 Address are given below:
- Each number must be between 0 and 255
- Must contain exactly 4 numbers separated by dots
Regex for Valid IP Addresses
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
**Explanation:
- **25[0-5]: Matches 250–255
- **2[0-4][0-9]: Matches 200–249
- **[01]?[0-9][0-9]?: Matches 0–199 (with optional leading 0 or 1)
- ****{3}:** First three numbers followed by dots
Below is the sample file (test2.txt) used in this article.

test2.txt
Python `
import re
with open('test2.txt', 'r') as fh: lines = fh.readlines()
pattern = re.compile(r'((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}'r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')
valid_ips = [] invalid_ips = []
for line in lines: line = line.strip() if pattern.fullmatch(line): valid_ips.append(line) else: invalid_ips.append(line)
print("Valid IPs:", valid_ips) print("Invalid IPs:", invalid_ips)
`
**Output
Valid IPs: ['192.168.4.164', '69.168.4.226', '32.89.31.164', '67.168.3.227']
Invalid IPs: ['000.0000.00.00', '192.168.1.1 912.456.123.123']
**Explanation:
- **for line in lines: line = line.strip(): Loop through each line and remove leading/trailing whitespace.
- **if pattern.fullmatch(line): **valid_ips.append(line): If line fully matches the IP pattern, add to valid_ips.
- **else: invalid_ips.append(line): Otherwise, add to invalid_ips.