3

大家好,这是我的第一篇文章

在过去的两天里,我在这里为 ipv4 地址实现验证而苦苦挣扎......问题是验证应该在数据库级别执行,这让像我这样的菜鸟很难

所以我必须做:

  1. 验证 ipv4 地址
  2. 如果 ip 中某处的前缀为 0,我必须将其删除(例如:123.013.221.011 应变为 123.13.221.11)

到目前为止我在触发器中的内容:

这不正常工作,所以我向你们寻求帮助......谢谢!

DELIMITER $$
CREATE TRIGGER validation_trigger BEFORE INSERT ON setting_parameters
FOR EACH ROW 
BEGIN 
-- PROXY RULES --
   IF(NEW.parameter_name LIKE '%proxy%') = true THEN 
     IF(INET_ATON(NEW.parameter_value)<INET_ATON('255.255.255.255'))=true THEN 
        IF(NEW.parameter_name LIKE '0%') = true THEN 
           SET NEW.parameter_value = SUBSTR(NEW.parameter_value,2);
        ELSE 
           SIGNAL SQLSTATE '12345'
           SET MESSAGE_TEXT = 'Wrong PROXY parameter values !';
        END IF;
     END IF;
   END IF;
4

2 回答 2

2

有预先实现的功能来检查 IP 地址的有效性。请检查https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html

只需调用 IS_IPV4()

于 2020-08-31T09:32:50.760 回答
1

Here is a suggestion. Consider implementing this functionality as a User Defined Functions (or UDF). This will allow you to write code in either c or c++ rather than SQL.

Alternatively, You can use REGEXP support in MySQL.

This is a solution for Part 1 of your question:

This example is for validating an IPV4 address using REGEXP

SELECT '123.1.2.3'
REGEXP '^([1-9]|[1-9][0-9]|1[013-9][0-9]|12[0-689]|2[0-4][1-9]|25[0-4])\.(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][1-9]|25[0-4])$'
;

SQL Fiddle Link

(Note: I have never used triggers myself. Hence cannot give you ready-to-use code. But you can use this example to make a trigger out of it)

I think solution for part 2 is a simple find-and-replace. Here again a REGEXP can be used to match all the patterns of 0, 00, .0, .00 and replace with a . (or nothing, if beginning of string)

Update 2:

Here is an SQL example to remove leading zeros. I did not have to use REGEXP here since CAST() did the magic!

SELECT ip, 
    CONCAT_WS('.',CAST(SUBSTRING_INDEX(ip,'.',1) as UNSIGNED), 
    CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',2),'.',-1) as UNSIGNED), 
    CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-2),'.',1) as UNSIGNED), 
    CAST(SUBSTRING_INDEX(ip,'.',-1) as UNSIGNED))  as Converted_IP
FROM ip_addr;

If ip_addr is a table with a column named ip and values like this

-------------    
IP
-------------
127.0.0.1
001.02.0.123
1.23.123.000
-------------

The SQL will Output:

-----------------------------
IP              CONVERTED_IP
-----------------------------
127.0.0.1       127.0.0.1
001.02.0.123    1.2.0.123
1.23.123.000    1.23.123.0
-----------------------------

SQL Fiddle Link

Update 3:

I think this solution by Michael Berkowski is awesome

于 2013-11-13T17:02:00.443 回答