c# ip address generator to SQL
I have the following python code I found on the internet, I would like to make 开发者_开发百科a table in a SQL database with every ipv4 address that there is. I dont code in python but its what I found.
My question is 1: Is there T-SQL code I can use to generate the table ? (one column ie 0.0.0.0-255.255.255.255)
2: Is how would I make this in c#? using the fastest method possible ? I know showing the results slows the console application down by 400 %
#!/usr/bin/env python
def generate_every_ip_address():
for octet_1 in range( 256 ):
for octet_2 in range( 256 ):
for octet_3 in range( 256 ):
for octet_4 in range( 256 ):
yield "%d.%d.%d.%d" % (octet_1, octet_2, octet_3, octet_4)
for ip_address in generate_every_ip_address():
print ip_address
Would this work?
DECLARE @a INTEGER
DECLARE @b INTEGER
DECLARE @c INTEGER
DECLARE @d INTEGER
DECLARE @IPADDRESS nvarchar(50)
set @a = 0
WHILE @a < 256
BEGIN
SET @b = 0
WHILE @b < 256
BEGIN
SET @c = 0
WHILE @c < 256
BEGIN
SET @d = 0
WHILE @d < 256
BEGIN
SET @IPADDRESS = CAST(@a AS nvarchar(3)) + '.' + CAST(@b AS nvarchar(3)) + '.' + CAST(@c AS nvarchar(3)) + '.' + CAST(@d AS nvarchar(3))
PRINT @IPADDRESS
SET @d = @d + 1
END
SET @c = @c + 1
END
SET @b = @b + 1
END
SET @a = @a + 1
END
To insert in batches of 16,581,375 rows would be quite straightforward using the following TSQL.
DECLARE @Counter INT
SET @Counter = 0
SET NOCOUNT ON ;
WHILE ( @Counter <= 255 )
BEGIN
RAISERROR('Procesing %d' ,0,1,@Counter) WITH NOWAIT ;
WITH Numbers ( N )
AS ( SELECT CAST(number AS VARCHAR(3))
FROM master.dbo.spt_values
WHERE type = 'P'
AND number BETWEEN 0 AND 255
)
INSERT INTO YourTable
( IPAddress
)
SELECT @Counter + '.' + N1.N + '.' + N2.N + '.' + N3.N
FROM Numbers N1 ,
Numbers N2 ,
Numbers N3
SET @Counter = @Counter + 1
END
Please just use an int IDENTITY column to store each IP address. They're only 32 bits. Fill your table up with whatever else you're storing.
精彩评论