mockIPv4 function
Generate random IPv4 address.
format
argument accepts integers in range from 0 to 255, separated
by dots(.
), which represent a group or octet in IPv4.
Group can also be represented with *
, which generates any
number for particular group.
Returns IP as String.
Example usage:
mockIPv4('192.168.*.*') // returns '192.168.ANY_NUMBER.ANY_NUMBER'
mockIPv4('*.168.*.*') // returns 'ANY_NUMBER.168.ANY_NUMBER.ANY_NUMBER'
mockIPv4() == mockIPv4('*.*.*.*')
Implementation
String mockIPv4([String format = '*.*.*.*']) {
var ip = format.split('.');
if (ip.length != 4) {
throw ArgumentError('Invalid IPv4 format - Must contain 4 groups');
}
var _ip = ip
.map((s) {
if (s == '*') {
return '${random.nextInt(255 + 1).toString()}.';
}
var parsedGroup = int.tryParse(s);
if (parsedGroup != null && parsedGroup >= 0 && parsedGroup <= 255) {
return '$s.';
} else {
throw ArgumentError('Integers must be in range of 0 and 255');
}
})
.toList()
.join();
return _ip.substring(0, _ip.length - 1);
}