Technical Article

Parsing an IP address into its separate octets

,

IP addresses are represented as xxx.xxx.xxx.xxx, where xxx is an integer between 0 and 255.  Each three-digit integer is called an octet, and all IP addresses comprise four octets.

Help-desk applications and administrative tools often store the IP addresses for a company's PCs in a database.  An IP address can be represented either as a single VARCHAR field (172.20.1.116), or as four separate INT fields representing each octet.  Why might it be better to store it as separate INT fields?  For one, it makes it easier to (for example) write a query to determine which subnet(s) a given set of addresses belongs to.  Secondly, it makes it possible to perform arithmetic and bitwise operations.

But what if you're importing data from a source that stores the entire IP address as a string value?  Is there an elegant way to parse out each octet?

SQL Server's PARSENAME function is used for parsing out the individual elements of a qualified SQL Server object reference (e.g., ServerName.DBName.Owner.Object).  Note that the format of a fully-qualified object reference is four elements separated by periods......which just happens to be the same as that of an IP address!  This means that you can use PARSENAME to parse out the individual elements of an IP address.

I have conveniently wrapped PARSENAME in my own user-defined function, ParseIP, which returns the 4 octets of an IP address as separate fields.

/*
Table-valued function ParseIP -
Parses an IP address and returns each octet as a separate field.

Syntax: SELECT * FROM ParseIP('<ip_address>')

Ex: SELECT * FROM ParseIP('172.20.1.116')
*/
CREATE FUNCTION ParseIP (@IPAddress varchar(15))

RETURNS TABLE

AS

RETURN
(
SELECT 
CAST(PARSENAME(@IPAddress, 4) AS INT) AS IP_Octet4,
CAST(PARSENAME(@IPAddress, 3) AS INT) AS IP_Octet3,
CAST(PARSENAME(@IPAddress, 2) AS INT) AS IP_Octet2,
CAST(PARSENAME(@IPAddress, 1) AS INT) AS IP_Octet1
)

Rate

2.5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

2.5 (2)

You rated this post out of 5. Change rating