0

In MySQL, I need to select all rows where a field is not an IP address (e.g. 12.32.243.43). Can this be done with MySQL only?

For example: I tried the following but it doesn't match.

select * from mytable where field not like '%.%.%.%' 
cmbuckley
  • 40,217
  • 9
  • 77
  • 91

2 Answers2

2

Sure can. You would be looking for something like:

SELECT * FROM `table` WHERE NOT( some_field REGEXP '^[0-9+]\.[0-9]+\.[0-9+]\.[0-9+]')
Menztrual
  • 40,867
  • 12
  • 57
  • 70
2

If using regular expression is not a requirement, this shall deliver the solution:

select stringBasedIp from x
where inet_aton(stringBasedIp) is null;


select stringBasedIp, (inet_aton(stringBasedIp) is null) as isInvalidIp
from x;

Sample data:

create table x(stringBasedIp varchar(16));

insert into x values
('255.255.255.255'),
('0.0.0.0'),
('0.0.0.300'),
('0.0.0.-1'),
('0.0.0.A'),
('192.168.0.1'),
('400.168.0.1'),
('12.32.243.43'),
('12.32.243.430');

Here are the list of invalid ip:

STRINGBASEDIP
0.0.0.300
0.0.0.-1
0.0.0.A
400.168.0.1
12.32.243.430

Live test: http://www.sqlfiddle.com/#!2/2a4ec/1

Michael Buen
  • 38,643
  • 9
  • 94
  • 118