Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
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 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.

Total article views: 624 | Views in the last 30 days: 4
 
Related Articles
FORUM

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[/...

FORUM

Select just three octets from IP number

Select just three octets from IP number

FORUM

Data Cleansing

address fields

FORUM

Datatype for IP addresses

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

FORUM

first element in sublist

first element in sublist

Tags
miscellaneous    
t-sql    
 
Contribute