Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Parsing an IP address into its separate octets

By Cade Bryant,

IP addresses are represented as, 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 (, 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.

Total article views: 620 | Views in the last 30 days: 2
Related Articles

Parsing an IP address into its separate octets

Comments posted to this topic are about the item [B]Parsing an IP address into its separate octets[/...


Select just three octets from IP number

Select just three octets from IP number


Data Cleansing

address fields


Datatype for IP addresses

What is the best datatype to use for an IP address table?


first element in sublist

first element in sublist


Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones