Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for valid host:port combination

Tags:

regex

php

Is there a way to check a valid host:port combination using regex and php?

The regular expression has to make sure that:

  • host is a valid IP (containing four 1-3 digit numbers separated by 3 dots, number in range of 1-255)
  • there is a delimiter :
  • port is a valid number between 0 and 65535
  • nothing else is allowed

Examples of valid combinations:

  1. 95.241.1.5:5423

  2. 2.8.5.2:65532

Examples of INvalid combinations:

  1. 1.2345.12.1:5441

  2. 15.852.32.455:151896841

  3. 65.112.15.32:48trololo


1 Answers

^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]):(?:6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{1,3}|[0-9])$

should work, but it's not pretty trying to match numbers with regexes...

In verbose format, a bit more readable:

^
(?:
 (?:
  25[0-5]|        # 250-255
  2[0-4][0-9]|    # 200-249
  1[0-9][0-9]|    # 100-199
  [1-9]?[0-9]     # 0-99
 )  
 \.               # .
){3}              # three times, last segment follows (no dot)
(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])
:                 # :
(?:
 6553[0-5]|       # 65530-65535
 655[0-2][0-9]|   # 65500-65529
 65[0-4][0-9]{2}| # 65000-65499
 6[0-4][0-9]{3}|  # 60000-64999
 [1-5][0-9]{4}|   # 10000-59999
 [1-9][0-9]{1,3}| # 10-9999
 [0-9]            # 0-9
)
$
like image 73
Tim Pietzcker Avatar answered Dec 08 '25 08:12

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!