[Python] IP 변환 함수
import socket, struct
def dottedQuadToNum(ip):
# IP Address 를 십진수로 변환
return struct.unpack('>L', socket.inet_aton(ip))[0]
def numToDottedQuad(n):
# 십진수를 IP Address로 변환
return socket.inet_ntoa(struct.pack('>L', n))
def makeMask(n):
"return a mask of n bits as a long integer"
return (2L<<n-1)-1
def ipToNetAndHost(ip, maskbits):
"return tuple (network, host) dotted-quad address given IP and mask size"
n = dottedQuadToNum(ip)
m = makeMask(maskbits)
host = n & m
net = n - host
return numToDottedQuad(net), numToDottedQuad(host)
def dottedQuadToNum(ip):
# IP Address 를 십진수로 변환
return struct.unpack('>L', socket.inet_aton(ip))[0]
def numToDottedQuad(n):
# 십진수를 IP Address로 변환
return socket.inet_ntoa(struct.pack('>L', n))
def makeMask(n):
"return a mask of n bits as a long integer"
return (2L<<n-1)-1
def ipToNetAndHost(ip, maskbits):
"return tuple (network, host) dotted-quad address given IP and mask size"
n = dottedQuadToNum(ip)
m = makeMask(maskbits)
host = n & m
net = n - host
return numToDottedQuad(net), numToDottedQuad(host)