함수 ip2int()

(함수 ip2long()에서 넘어옴)

1 개요[ | ]

함수 ip2int()
함수 ip2long()
INET_ATON()

2 Bash[ | ]

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

ip2long 0.0.0.0
ip2long 0.0.0.1
ip2long 0.0.1.0
ip2long 255.255.255.255
ip2long 135.79.246.80
# 0
# 1
# 256
# 4294967295
# 2270164560
ip2long 0.0.0.256
ip2long 0.0.0.0.0
ip2long 0.0.0.00
ip2long 135.79.246.080
# -1
# -1
# -1
# -1

3 Go[ | ]

package main

import (
	"encoding/binary"
	"fmt"
	"net"
)

func ip2int(ipString string) int {
	ip := net.ParseIP(ipString)
	if ip == nil {
		return -1
	}
	return int(binary.BigEndian.Uint32(ip.To4()))
}
func main() {
	fmt.Println(ip2int("0.0.0.0"))         // 0
	fmt.Println(ip2int("0.0.0.1"))         // 1
	fmt.Println(ip2int("0.0.1.0"))         // 256
	fmt.Println(ip2int("135.79.246.80"))   // 2270164560
	fmt.Println(ip2int("255.255.255.255")) // 4294967295

	fmt.Println(ip2int("0.0.0.256"))      // -1
	fmt.Println(ip2int("0.0.0.0.0"))      // -1
	fmt.Println(ip2int("0.0.0.00"))       // -1
	fmt.Println(ip2int("135.79.246.080")) // -1
}

4 SQL[ | ]

4.1 MySQL[ | ]

SELECT INET_ATON('0.0.0.0');
-- 0
SELECT INET_ATON('0.0.0.1');
-- 1
SELECT INET_ATON('0.0.1.0');
-- 256

SELECT INET_ATON('255.255.255.255');
-- 4294967295
SELECT INET_ATON('135.79.246.80');
-- 2270164560

5 PHP[ | ]

echo ip2long('0.0.0.0');
# 0
echo ip2long('0.0.0.1');
# 1
echo ip2long('0.0.1.0');
# 256
echo ip2long('255.255.255.255');
// 4294967295
var_dump( ip2long('135.79.246.80') );
// int(2270164560)
var_dump( ip2long('135.79.246.080') );
// bool(false)

6 Python[ | ]

from socket import inet_aton
from struct import unpack

def ip2long(ip_addr):
	try: return unpack("!L", inet_aton(ip_addr))[0]
	except IOError: return None

print( ip2long('0.0.0.0') );
print( ip2long('0.0.0.1') );
print( ip2long('0.0.1.0') );
# 0
# 1
# 256
print( ip2long('255.255.255.255') );
print( ip2long('135.79.246.80') );
# 4294967295
# 2270164560
print( ip2long('135.79.246.080') );
# None

7 같이 보기[ | ]

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