index.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // @ts-nocheck
  2. // #ifndef APP-ANDROID || APP-HARMONY || APP-IOS
  3. type UTSJSONObject = {
  4. version : string | number | null;
  5. };
  6. // #endif
  7. // #ifdef APP-ANDROID || APP-HARMONY || APP-IOS
  8. // type Options = UTSJSONObject
  9. // #endif
  10. const IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
  11. const IPv4AddressFormat = `(${IPv4SegmentFormat}\\.){3}${IPv4SegmentFormat}`;
  12. const IPv4AddressRegExp = new RegExp(`^${IPv4AddressFormat}$`);
  13. const IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})';
  14. const IPv6AddressRegExp = new RegExp(
  15. '^(' +
  16. `(?:${IPv6SegmentFormat}:){7}(?:${IPv6SegmentFormat}|:)|` +
  17. `(?:${IPv6SegmentFormat}:){6}(?:${IPv4AddressFormat}|:${IPv6SegmentFormat}|:)|` +
  18. `(?:${IPv6SegmentFormat}:){5}(?::${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,2}|:)|` +
  19. `(?:${IPv6SegmentFormat}:){4}(?:(:${IPv6SegmentFormat}){0,1}:${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,3}|:)|` +
  20. `(?:${IPv6SegmentFormat}:){3}(?:(:${IPv6SegmentFormat}){0,2}:${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,4}|:)|` +
  21. `(?:${IPv6SegmentFormat}:){2}(?:(:${IPv6SegmentFormat}){0,3}:${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,5}|:)|` +
  22. `(?:${IPv6SegmentFormat}:){1}(?:(:${IPv6SegmentFormat}){0,4}:${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,6}|:)|` +
  23. `(?::((?::${IPv6SegmentFormat}){0,5}:${IPv4AddressFormat}|(?::${IPv6SegmentFormat}){1,7}|:))` +
  24. ')(%[0-9a-zA-Z.]{1,})?$'
  25. );
  26. /**
  27. * 验证IP地址格式
  28. * @param {string} ipAddress - 要验证的IP地址
  29. * @param {Options|string|number} options - 配置选项或版本号
  30. * @returns {boolean} 是否匹配有效的IP地址格式
  31. */
  32. export function isIP(ipAddress : string | null, options : UTSJSONObject | string | number | null = null) : boolean {
  33. // assertString(ipAddress);
  34. if(ipAddress == null) return false
  35. let version : string | number | null;
  36. if (typeof options == 'object') {
  37. version = (options as UTSJSONObject|null)?.['version'];
  38. } else {
  39. version = options;
  40. }
  41. const versionStr = version != null ? `${version}` : '';
  42. if (versionStr == '') {
  43. return isIP(ipAddress, 4) || isIP(ipAddress, 6);
  44. }
  45. if (versionStr == '4') {
  46. return IPv4AddressRegExp.test(ipAddress.trim());
  47. }
  48. if (versionStr == '6') {
  49. return IPv6AddressRegExp.test(ipAddress.trim());
  50. }
  51. return false;
  52. }