SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Parsing an IP address into its separate octets

By Cade Bryant, 2004/02/25

Total article views: 73 | Views in the last 30 days: 3

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.

By Cade Bryant, 2004/02/25

Total article views: 73 | Views in the last 30 days: 3
Your response
 
 
Related tags

Miscellaneous    
T-SQL Aids    
 
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com