함수 is_ip()


함수 is_ip()

1 Bash[ | ]

  • 순수 bash
function is_ip() {
	IFS='.' read -ra nums <<< "$1"
	if [ ${#nums[@]} -ne 4 ]; then echo 0; return; fi
	for num in "${nums[@]}"; do
		if [ "$num" != "$((10#$num))" ]||[ $num -lt 0 ]||[ $num -gt 255 ]; then echo 0; return; fi
	done	
	echo 1
}

# 1
is_ip 0.0.0.0
is_ip 0.0.0.1
is_ip 0.0.1.0
is_ip 255.255.255.255
is_ip 135.79.246.80

# 0
is_ip 0.0.0.256
is_ip 0.0.0.0.0
is_ip 0.0.0.00
is_ip 135.79.246.080
  • 신버전 ipcalc 활용(v0.41)
echo $((`ipcalc 135.79.246.80 | grep INVALID | wc -l`^1))
# 1
echo $((`ipcalc 135.79.246.280 | grep INVALID | wc -l`^1))
# 0
ipcalc -s -c 135.79.246.80; echo $(($?^1))
# 1
ipcalc -s -c 135.79.246.280; echo $(($?^1))
# 0

2 PHP[ | ]

function is_ip($ip) { return ip2long($ip)?true:false; }

# true
var_dump( is_ip('1.1.1.1') );
var_dump( is_ip('135.79.246.80') );

# false
var_dump( is_ip('1.1.1.1.') );
var_dump( is_ip('1.1.1.256') );
var_dump( is_ip('135.79.256.080') );

3 Python[ | ]

import ipaddress
def is_ip(ip):
    try:
        ipaddress.ip_address(ip)
    except ValueError:
        return False
    return True
    
# True
print( is_ip('1.1.1.1') )
print( is_ip('192.168.0.1') )
print( is_ip('135.79.246.80') )

# False
print( is_ip('1.1.1.1.') )
print( is_ip('1.1.1.256') )
print( is_ip('192.168.0.256') )
print( is_ip('135.79.256.080') )

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}