PHP has a great many tools for interacting with a network and also with the Internet. In this article we will look at some of those tools and functions to see how we can use them to make our scripts more useful in a network environment. This article is the first of two parts.
While each machine on the TCP/IP network must have at least one IP address, there is no requirement that it should have a DNS name. Thus it is entirely possible that a machine may have an IP address and no DNS entry; in which case the function returns the ip_address argument itself. In fact, if an error occurs, the return value of the function is the ip_address argument.
int getprotobyname(string name)
This function returns the protocol number associated with a TCP/IP protocol, which is a unique integer associated with the protocol name that is passed to it as an argument. The name-to-protocol mapping is stored in a text file, usually in /etc/protocols on UNIX-derived systems and %SystemRoot%System32driversetcprotocol on Microsoft Windows NT or Windows 2000.
string getprotobynumber(int number)
This function has just the opposite functionality of the getprotobyname() function in that, given the protocol number as an argument, it displays the protocol name.
int getservbyname(string service, string protocol)
We need to obtain the well-known port number at which a service is running before our client can connect to it. This function takes a service name, and the transport protocol, that is either TCP or UDP, and returns the port number associated with the service. On most UNIX machines the port number to service mapping is specified in the /etc/services file:
$protocol = "smtp";
$portNum = getservbyname($protocol, "tcp");
echo("The port number of the $protocol service is $portNum");
This prints the port number of the Simple Mail Transfer Protocol as 25. On most UNIX machines the information mapping the protocol name with the protocol number is available in the /etc/protocol file.
string getservbyport(int port, string protocol)
This function has just the opposite functionality of getservbyname(); it prints the service name associated with the port number argument. The protocol argument indicates the transport protocol (that is TCP or UDP) that the service is implemented over.
As we saw, the getprotobyname(), getprotobynumber(), getservbyname(), and getservbynumber() functions obtain their information from files on the local file system (on most platforms). Therefore, they are not really DNS functions, but we examine them in this context since they are essentially resolver functions.