Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate port number

I'm using this regex (6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3} to validate port numbers. Somehow this is not working. What is wrong with this? Can anybody point me out.

like image 809
Soham Dasgupta Avatar asked Oct 19 '12 05:10

Soham Dasgupta


People also ask

How do I validate a port number in Python?

PortNumber = int(input("Enter a port number: ")) if 1<= PortNumber <= 65535: print('This is a VALID port number. ') else: print('This is NOT a valid port number. ')

What is TCP port range?

Port numbers range from 0 to 65536, but only ports numbers 0 to 1024 are reserved for privileged services and designated as well-known ports. This list of well-known port numbers specifies the port used by the server process as its contact port.

Why do we need to use port number when communicating with a remote application?

A port number is a way to identify a specific process to which an internet or other network message is to be forwarded when it arrives at a server. All network-connected devices come equipped with standardized ports that have an assigned number.


1 Answers

What exactly do you mean by not working?

You could try something like so: ^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$ (obtained from here).

This will make sure that any given string is numeric and between the range of 0 and 65535.

Assuming your regular expression matches the same range, it is missing the start and end anchors (^ and $ respectively), so it would allow other strings besides the actual port.

Update 2 Feb 2022: Fixed the regex to reject values like 00 etc. The updated regex is sourced from the comment below. This regex can be better understood and visualized here: https://www.debuggex.com/r/jjEFZZQ34aPvCBMA

like image 152
npinti Avatar answered Oct 17 '22 04:10

npinti