Make a try with regex.
Code: Select all
EnableExplicit
Procedure FindIPAddress(Text$, ipv=4)
Protected ipv$, ipv4$, ipv6$, ipv46$
Protected IPRegex, NbResults, i
Dim Result$(0)
; ============= REGEX =======================================================================================================
;All regex found somewhere on the web
;ipv4
ipv4$="(?:(?:0|1[\d]{0,2}|2(?:[0-4]\d?|5[0-5]?|[6-9])?|[3-9]\d?)\.){3}(?:0|1[\d]{0,2}|2(?:[0-4]\d?|5[0-5]?|[6-9])?|[3-9]\d?)"
; This regexp accepts 1.2.3.4 but Not 001.002.003.004 which is invalid in IPv4 addresses used
; in URLs And email addresses, which forbids leading zeroes. Extra leading zeroes would transform
; the apparent IPv4 address into a domain name
;ipv6 several regex
ipv6$="((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))b)\.){3}(b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))b)\.){3}(b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))b)\.){3}(b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\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0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:)))(%.+)?\s*$"
; ============= END REGEX =======================================================================================================
;Select ipv4 or ipv6 or both
Select ipv
Case 4
ipv$=ipv4$
Case 6
ipv$=ipv6$
Case 46
ipv$=ipv46$
Default
Debug "unknown"
End
EndSelect
; Try to create regex
IPRegex=CreateRegularExpression(#PB_Any,ipv$ )
If IPRegex
; Try to find IP
NbResults = ExtractRegularExpression(IPRegex, Text$, result$())
; How many IP found
Debug "Nb matchs found: " + NbResults
; Display IPs
For i = 0 To NbResults - 1
Debug Result$(i)
Next
Else
MessageRequester("Error", RegularExpressionError())
EndIf
EndProcedure
FindIPAddress("127.0.0.1", 4)
FindIPAddress("2001:41D0:1:2E4e::1", 6)
FindIPAddress("127.0.0.1", 46) ; oops, sorry there is a bug
FindIPAddress("2001:41D0:1:2E4e::1", 46)
FindIPAddress("2001:41D0:1:2E4e::1", 66)
;TODO Replace: 4,6 and 46 by #ipv4, #ipv6 and #ipv4|#ipv6
M.