In PHP, getservbyname() looks up the port number for a named Internet service and protocol, using the same kind of table as /etc/services on Unix-like systems.
You pass a service name such as "http" or "ftp" and a protocol of "tcp" or "udp". If the name is known, you get the port as an integer. If it is not found, the function returns false.
Syntax
Call getservbyname() with the values you need. Start with this line.
PHP
$port = getservbyname("http", "tcp");
Call
What it does
getservbyname("http", "tcp")
Returns 80 on a normal services table.
getservbyname("https", "tcp")
Returns 443 for HTTPS over TCP.
getservbyname("no-such-svc", "tcp")
Returns false when the service name is unknown.
Service and protocol names are lowercase strings. The exact list depends on the host operating system, but common names like http, https, ftp, ssh and smtp are almost always present.
We compare with === false so a real port is never treated as failure.
The host and port are joined with a colon for display.
In real code you would pass that port to fsockopen() or a similar call.
Frequently Asked Questions
It returns the port number for a named Internet service and protocol, using the same kind of table as /etc/services. For example, getservbyname("http", "tcp") returns 80.
Use lowercase "tcp" or "udp". Those are the values the services table expects.
The function returns false. Check the result before you use it as a port number.
getservbyname() turns a name into a port. getservbyport() turns a port number into a service name.
Common ports are the same almost everywhere, but custom or rare names depend on the host operating system table.