C.W.K.
Stream
Lesson 03 of 12 · published

IP 주소 검증

~8 min · ip, validation

Level 0패턴 호기심
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

순진한 패턴

IPv4 주소가 점으로 분리된 숫자 넷: \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}. 검증 위한 anchor: ^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$.

이게 진짜 IP 아닌 999.999.999.999 받음. 각 octet 가 0-255.

엄격한 패턴

각 octet 0-255, 정규식으로 표현:

(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)

읽기: 25[0-5] (250-255), OR 2[0-4]\d (200-249), OR 1\d\d (100-199), OR [1-9]?\d (0-99 + optional 앞 자리).

풀 IPv4 + anchor:

^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$

못생겼지만 정확.

OR — 표준 라이브러리에 시키기

실제 검증엔 IP 파싱 라이브러리: Python ipaddress.ip_address(s). IPv4, IPv6, CIDR notation, 정규식이 못 잡는 엣지 케이스 처리. 정규식이 IP-shape 문자열 FINDING 용; 라이브러리가 VALIDATING 용.

IPv6 — 시도조차 X

IPv6 가 4 hex 자리 8 그룹, 여러 압축 형태 (::, dotted-quad embedded). 정규식이 100 자 넘고 여전히 모든 유효 형태 못 잡음. Python 에 ipaddress, Go 에 net.ParseIP.

Code

IP 패턴·python
import re

# 순진 — IP-shape 문자열 찾음, octet 범위 검증 X
IP_NAIVE = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
re.findall(IP_NAIVE, 'server at 192.168.1.1 and 999.999.999.999')
# ['192.168.1.1', '999.999.999.999']  — 둘 다 'match'

# 엄격 — 각 octet 0-255
OCTET = r'(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)'
IP_STRICT = re.compile(rf'^{OCTET}\.{OCTET}\.{OCTET}\.{OCTET}$')

bool(IP_STRICT.fullmatch('192.168.1.1'))      # True
bool(IP_STRICT.fullmatch('999.999.999.999'))  # False
bool(IP_STRICT.fullmatch('256.0.0.1'))        # False

# 베스트: 정규식으로 추출, 라이브러리로 검증
import ipaddress
for candidate in re.findall(IP_NAIVE, 'log: 192.168.1.1 and 999.999.999.999'):
    try:
        addr = ipaddress.ip_address(candidate)
        print(f'{addr} valid')
    except ValueError:
        print(f'{candidate} not a real IP')
# 192.168.1.1 valid
# 999.999.999.999 not a real IP

External links

Exercise

로그 파일 받아서 모든 IP-shape 문자열 추출, 진짜 IP 인 것만 (ipaddress.ip_address 사용) print 하는 스크립트 작성. 작은 로그에 돌려서 추출과 검증 차이 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.