Use getservbyport() when you need to resolves a registered port and protocol to a service name in a PHP application. The examples below show the actual operation and its limitations.
What Is getservbyport() in PHP?
Resolves a registered port and protocol to a service name. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
getservbyport(int $port, string $protocol): string|false
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
var_dump(getservbyport(80,"tcp"));
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Example 2: Different Input or Behavior
<?php
var_dump(getservbyport(53,"udp"));
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Practical Example: Applying the Function
<?php
$service = getservbyport(443,"tcp"); echo $service === false ? "Unknown service" : $service;
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Important Behavior and Edge Cases
The OS service database supplies names; it does not check whether a port is actually listening.
Comparison With Related Functions
| Approach | Difference |
|---|---|
getservbyport() | Resolves a registered port and protocol to a service name. |
| Related operation | getservbyname() resolves the other direction. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | The OS service database supplies names; it does not check whether a port is actually listening. |
| Confusing this function with a related operation | getservbyname() resolves the other direction. |
Key Takeaways
- Resolves a registered port and protocol to a service name.
- The OS service database supplies names; it does not check whether a port is actually listening.
- getservbyname() resolves the other direction.
Use getservbyport() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.