PHP | getservbyname() Function

The getservbyname() function is an inbuilt function in PHP which returns the port number for given protocol and Internet service.

Syntax:

int getservbyname( string $service, string $protocol )

Parameters: This function accepts two parameters as mentioned above and described below:



  • $protocol: It is required parameter. It specifies protocol name, like tcp, udp etc in string format.
  • $service: It is required parameter. It specifies the Internet service name, like http int string format.

Return Value: This function returns the port number on success or False if service or protocol not found.

Note: This function is available for PHP 4.0.0 and newer version.

Below programs illustrate the getservbyname() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Use getservbyname() function to get
// port number associated with an 
// Internet service and protocol
$portnum = getservbyname("http", "tcp");
  
// Display the result
echo $portnum;
  
?>

chevron_right


Output:

80

Program 2: This program checks multiple services.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// Create an array of services
$services = array("ftp", "ssh",
            "telnet", "http", "https");
  
// Loop run for each services
foreach( $services as $index) {
      
    // Use getservbyname() function to get
    // the port number associated with an 
    // Internet service and protocol
    echo getservbyname($index, "tcp"
            . ": " . $index . "<br>";
}
  
?>

chevron_right


Output:

21: ftp
22: ssh
23: telnet
80: http
443: https

Reference: https://www.php.net/manual/en/function.getservbyname.php



My Personal Notes arrow_drop_up

I am unrecognized crazy being with random thoughts

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.