I'm working on a function to convert the string representation of an IP into its varbinary(4/16) form.

Right now, I have this:

@stringIP = ''
    CAST(PARSENAME(@stringIP, 4) as tinyint),
    CAST(PARSENAME(@stringIP, 3) as tinyint),
    CAST(PARSENAME(@stringIP, 2) as tinyint),
    CAST(PARSENAME(@stringIP, 1) as tinyint)

This breaks up my IPv4 Address very well; but I need to figure out how to insert it into a varbinary(4) so I can insert the data to my table. I cannot find ANY TSQL syntax to combine these four tinyints into a varbinary(4) -- I can only find C#/VB examples using paramterized SQL. This is fine and good, but I'm trying to create an SQL Function do use in an INSTEAD OF INSERT trigger.

  • I am open to other/better ways to parse the IP as well, but I've found a few examples using PARSENAME for IPv4 and it seems to work well...
    – Nate
    Jan 26, 2012 at 22:57
  • Possible duplicate of stackoverflow.com/questions/695568/…
    – GSerg
    Jan 26, 2012 at 23:01

1 Answer 1

@stringIP = ''
    cast(CAST(PARSENAME(@stringIP, 4) as tinyint) as varbinary(1)) +
    cast(CAST(PARSENAME(@stringIP, 3) as tinyint) as varbinary(1)) +
    cast(CAST(PARSENAME(@stringIP, 2) as tinyint) as varbinary(1)) +
    cast(CAST(PARSENAME(@stringIP, 1) as tinyint) as varbinary(1))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.