Jump to content

Module:IP

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 02:45, 12 July 2016 (create outline of a library for dealing with IP addresses). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

-- IP library
-- This library contains classes for working with IP addresses and IP ranges.

local libraryUtil = require('libraryUtil')

--------------------------------------------------------------------------------
-- IPAddress class
-- Represents a single ipv4 or ipv6 address.
--------------------------------------------------------------------------------

local IPAddress = {}

function IPAddress.new(ip)
	local mt = {}
	local obj = setmetatable({}, mt)

	local normalizedIP = ip
	local version = 4

	function obj:getIP()
		return normalizedIP
	end

	function obj:setIP(ip)
		normalizedIP = ip
	end

	function obj:getVersion()
		return version
	end

	function obj:isIPv4()
		return version == 4
	end

	function obj:isIPv6()
		return version == 6
	end

	function obj:isInRange(range)
		return false
	end

	function mt:__eq(obj)
		return false
	end

	function mt:__tostring()
		return normalizedIP
	end

	return obj
end

--------------------------------------------------------------------------------
-- IPRange class
-- Represents a range of ipv4 or ipv6 addresses.
--------------------------------------------------------------------------------

local IPRange = {}

function IPRange.new(startIp, endIp)
	local mt = {}
	local obj = setmetatable({}, mt)

	local normalizedStartIP = startIp
	local normalizedEndIP = endIp
	local version = 4

	function obj:getStartIP()
		return normalizedStartIP
	end

	function obj:setStartIP(ip)
		normalizedStartIP = ip
	end

	function obj:getEndIP()
		return normalizedEndIP
	end

	function obj:setEndIP(ip)
		normalizedEndIP = ip
	end

	function obj:getVersion()
		return version
	end

	function obj:isIPv4()
		return version == 4
	end

	function obj:isIPv6()
		return version == 6
	end

	function obj:containsIP(ip)
		return false
	end

	function mt:__eq(obj)
		return false
	end

	function mt:__tostring()
		return normalizedIP
	end

	return obj
end

return {
	IPAddress = IPAddress,
	IPRange = IPRange,
}