I'm creating a small IP:PORT scraper in PHP. The problem is that I'm pretty unfamiliar with RegEx.
So I've been piecing together what I can.
Here's what I've got:
/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):([0-9]{1,5})\b/
I know this isn't the best. At least not the end to grab the port, because it means that ports will be able to be things like 99999.
Also, it seems to return two matches this way. The IP:PORT and the PORT. I just need it to grab the full IP:PORT, not one or the other.
\d{1,3}\b will match any IP address just fine. But will also match 999.999. 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.
All you have to do is type “netstat -a” on Command Prompt and hit the Enter button. This will populate a list of your active TCP connections. The port numbers will be shown after the IP address and the two are separated by a colon.
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
Your regex is fine so I will just concentrate on the port itself. This regex :
(?:: #Match the :
(?![7-9]\d\d\d\d) #Ignrore anything above 7....
(?!6[6-9]\d\d\d) #Ignore anything abovr 69...
(?!65[6-9]\d\d) #etc...
(?!655[4-9]\d)
(?!6553[6-9])
(?!0+) #ignore complete 0(s)
(?<Port>\d{1,5})
)?
Will optionally catch any valid port number and store it to named group port.
Note: free spacing must be enabled:
if (preg_match(
'/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
(?::
(?![7-9]\d\d\d\d) #Ignrore anything above 7....
(?!6[6-9]\d\d\d) #Ignore anything abovr 69...
(?!65[6-9]\d\d) #etc...
(?!655[4-9]\d)
(?!6553[6-9])
(?!0+) #ignore complete 0(s)
(?P<Port>\d{1,5})
)?
\b/x',
$subject)) {
# Successful match
}
I've posted a regular expression below what matches either ip or ip and port.
$ip = '111.222.333.444';
if ( preg_match('/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\:?([0-9]{1,5})?/', $ip, $match) ) {
echo 'ip: ' . $match['1'] . (isset($match['2']) ? ' port: ' . $match['2'] : '');
}
You could try this:
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):\d{1,5}\b
There are a few examples for IP matching here. Just take any of them and put :\d{1,5}\b
on the end (to match a port).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With