Last active
March 23, 2024 19:57
-
-
Save matthew-n/f59f48db5628d705499d000c2a9fd96f to your computer and use it in GitHub Desktop.
fun with IP Addresses in MSSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE FUNCTION dbo.udf_ipv4_format (@addr binary(16) ) | |
RETURNS varchar(20) with SCHEMABINDING AS | |
BEGIN | |
return IIF(SUBSTRING(@addr,0,8)=0, | |
CONCAT( | |
CAST(SUBSTRING(@addr,13,1) AS INT),'.', | |
CAST(SUBSTRING(@addr,14,1) AS INT),'.', | |
CAST(SUBSTRING(@addr,15,1) AS INT),'.', | |
CAST(SUBSTRING(@addr,16,1) AS INT) | |
),NULL) | |
END; | |
GO | |
CREATE TABLE dbo.Host ( | |
HostID INT NOT NULL IDENTITY, | |
HostName VARCHAR(512) NOT NULL, | |
-- Internal IP's unformated IPv6 | |
IPaddress BINARY(16) NOT NULL | |
CONSTRAINT DF_Host_IPAddress DEFAULT (0x0), | |
IPV4 AS dbo.udf_ipv4_format(IPaddress) PERSISTED, | |
CONSTRAINT PK_Host PRIMARY KEY CLUSTERED(HostID), | |
CONSTRAINT UQ_HostName UNIQUE (HostName), | |
CONSTRAINT UQ_HostAddress UNIQUE (IPV4) | |
); | |
GO | |
insert into dbo.host(HostName, IPaddress) | |
values('my_host', 0x00000000000000000000FFFFFFFFFFFF), | |
('test_host', 0x00000000000000000000ffffac107601); | |
GO | |
select * from dbo.host; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment