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.
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. ')
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.
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.
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
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