PHP Socket Programming

You might not know this, but PHP comes with a very capable socket programming API. These socket functions now include almost everything you would need for socket-based client-server communication over TCP/IP, and can be easily deployed to build simple network applications.

PHP & TCP/IP Sockets

This is a quick guide/tutorial to learning socket programming in php. Socket programming php is very similar to C. Most functions are similar in names, parameters and output. However unlike C, socket programs written in php would run the same way on any os that has php installed. So the code does not need any platform specific changes (mostly).

To summarize the basics, sockets are the fundamental “things” behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a socket.

Before you begin

This tutorial assumes that you already know php and also how to run php scripts from the commandline/terminal. Php scripts are normally run from inside the browser by placing them in the apache root directory like /var/www. However these commandline programs can be run from any directory. They can be run from browsers as well.

So lets begin with sockets.

Creating a socket

This first thing to do is create a socket. The socket_create function does this.
Here is a code sample :

Function socket_create creates a socket and returns a socket descriptor which can be used in other network commands.

The above code will create a socket with the following properties …

Address Family : AF_INET (this is IP version 4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Protocol : 0 [ or IPPROTO_IP This is IP protocol]

Error handling

If any of the socket functions fail then the error information can be retrieved using the socket_last_error and socket_strerror functions.

Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com

Note:

Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.

Connect to a Server

We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to. So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.

The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.

Run the program

$ php /var/www/socket.php
Socket created
Connection established

It creates a socket and then connects. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection. This logic can be used to build a port scanner.

OK, so we are now connected. Lets do the next thing , sending some data to the remote server.

Quick Note

The concept of “connections” apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable “stream” of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.

Other sockets like UDP , ICMP , ARP dont have a concept of “connection”. These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.

Sending Data

Function send will simply send data. It needs the socket descriptor , the data to send and its size.
Here is a very simple example of sending some data to google.com ip :

In the above example , we first connect to an ip address and then send the string message “GET / HTTP/1.1\r\n\r\n” to it.
The message is actually a http command to fetch the mainpage of a website.

Now that we have send some data , its time to receive a reply from the server. So lets do it.

Note

When sending data to a socket you are basically writing data to that socket. This is similar to writing data to a file. Hence you can also use the write function to send data to a socket. Later in this tutorial we shall use write function to send data.

Receiving Data

Function recv is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.

Here is the output of the above code :

We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!

Now that we have received our reply, its time to close the socket.

Close socket

Function socket_close is used to close the socket.

Lets Revise

So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply

Its useful to know that your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch data.

The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.

Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just in case you need them.

Get IP address of a hostname/domain

When connecting to a remote host , it is necessary to have its IP address. Function gethostbyname is used for this purpose. It takes the domain name as the parameter and returns the ip address.

Quick example

So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.

Server Programming

OK now onto server things. Servers basically do the following :

1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send

We have already learnt how to open a socket. So the next thing would be to bind it.

Bind a socket

Function bind can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.

Quick example

Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.

This makes it obvious that you cannot have 2 sockets bound to the same port. There are exceptions to this rule but we shall look into that in some other article.

Listen for connections

After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function socket_listen is used to put the socket in listening mode. Just add the following line after bind.

The second parameter of the function socket_listen is called backlog. It controls the number of incoming connections that are kept “waiting” if the program is already busy. So by specifying 10, it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected. This will be more clear after checking socket_accept.

Now comes the main part of accepting new connections.

Accept connection

Function socket_accept is used for this.

Output

Run the program. It should show

$ php /var/www/server.php
Socket created
Socket bind OK
Socket listen OK
Waiting for incoming connections…

So now this program is waiting for incoming connections on port 5000. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type

$ telnet localhost 5000

It will immediately show

$ telnet localhost 5000
Trying 127.0.0.1…
Connected to localhost.
Escape character is ‘^]’.
Connection closed by foreign host.

And the server output will show

Client 127.0.0.1 : 36689 is now connected to us.

So we can see that the client connected to the server. Try the above steps till you get it working perfect.

Note

The socket_getpeername function is used to get details about the client which is connected to the server via a particular socket.

We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.

Function socket_write can be used to write something to the socket of the incoming connection and the client should see it. Here is an example :

Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :

So the client(telnet) received a reply from server.

We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.

It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time.

Live Server

So a live server will be alive always. Lets code this up

We havent done a lot there. Just put the socket_accept in a loop.

Now run the server program in 1 terminal , and open 3 other terminals.
From each of the 3 terminal do a telnet to the server port.

Each of the telnet terminal would show :

$ telnet localhost 5000
Trying 127.0.0.1…
Connected to localhost.
Escape character is ‘^]’.
happy
OK .. happy
Connection closed by foreign host.

And the server terminal would show

$ php /var/www/server.php
Socket created
Socket bind OK
Socket listen OK
Waiting for incoming connections…
Client 127.0.0.1 : 37119 is now connected to us.
Client 127.0.0.1 : 37122 is now connected to us.
Client 127.0.0.1 : 37123 is now connected to us.

So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show “Connection closed by foreign host.”

Good so far. But still there is not effective communication between the server and the client. The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.

Handling Connections

To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
However php does not support threading directly.

Another method is to use the select function. The select function basically ‘polls’ or observers a set of sockets for certain events like if its readable, or writable or had a problem or not etc.
So the select function can be used to monitor multiple clients and check which client has send a message.

Quick Example

Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.

The telnet terminals would show :

The server terminal might look like this

The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look

So now we have a server thats communicative.

For more please visit.

http://www.phpjavascript.com/

Spread the love
  • 8
    Shares
  • 8
    Shares

Leave a Reply

Your email address will not be published. Required fields are marked *