Php and 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 summarise 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 : 1$sock = socket_create(AF_INET, SOCK_STREAM, 0); 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. 1if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) 2{ $errorcode = socket_last_error(); 3 $errormsg = socket_strerror($errorcode); 4 5 die("Couldn't create socket: [$errorcode] $errormsg \n"); 6}

com Note Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol.235.125. But what next ? Next we shall try to connect to some server using this socket. SOCK_STREAM.php Socket created Connection established . We can connect to www. In this tutorial we shall stick to SOCK_STREAM or TCP sockets. 19 Run the program $ php /var/www/socket. IP address and port number to connect to. Connect to a Server We connect to a remote server on a certain port number.com as a sample. 5 6 die("Couldn't create socket: [$errorcode] $errormsg \n").google. So you need to know the IP address of the remote server you are connecting to. 7 } 8 9 echo "Socket created \n". So we need 2 things . Here is a code sample. so you have created a socket successfully. 16} 17 18echo "Connection established \n". The last thing needed is the connect function. Here we used the ip address of google. 4 $errormsg = socket_strerror($errorcode).7 8echo "Socket created". 14 15 die("Could not connect: [$errorcode] $errormsg \n"). 0))) 3 { $errorcode = socket_last_error(). It needs a socket and a sockaddr structure to connect to. A little later on we shall see how to find out the ip address of a given domain name. 13 $errormsg = socket_strerror($errorcode). 9 Ok . 80)) 12{ $errorcode = socket_last_error(). '74. 1 2 if(!($sock = socket_create(AF_INET. This type of socket is nonconnection socket. 10 11if(!socket_connect($sock .20' .

3 $errormsg = socket_strerror($errorcode). '74. Sending Data Function send will simply send data. . $errormsg = socket_strerror($errorcode). Here is a very simple example of sending some data to google. $message . the data to send and its size. strlen($message) . ARP dont have a concept of "connection". 9 //Connect socket to remote server 10if(!socket_connect($sock . 0))) 2 { $errorcode = socket_last_error(). 13 14 die("Could not connect: [$errorcode] $errormsg \n"). 25 26 die("Could not send data: [$errorcode] $errormsg \n"). 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. 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.It creates a socket and then connects. 15 } 16 17echo "Connection established \n".1\r\n\r\n".20' .235. 0)) 23{ $errorcode = socket_last_error(). 24 $errormsg = socket_strerror($errorcode). Other sockets like UDP . Think of this as a pipe which is not interfered by other data. 20 21//Send the message to the server 22if( ! socket_send ( $sock . 6 } 7 8 echo "Socket created \n". ICMP . Lets do the next thing . Which means you keep sending or receiving packets from anybody and everybody. 4 5 die("Couldn't create socket: [$errorcode] $errormsg \n"). 80)) 11{ 12 $errorcode = socket_last_error().com ip : 1 if(!($sock = socket_create(AF_INET. These are non-connection based communication. OK. sending some data to the remote server. SOCK_STREAM.125. It needs the socket descriptor . 18 19$message = "GET / HTTP/1. so we are now connected. This logic can be used to build a port scanner.

20' . In the following example we shall send the same message as the last example and receive a reply from the server. $errormsg = socket_strerror($errorcode). 22 23//Send the message to the server 24if( ! socket_send ( $sock . The message is actually a http command to fetch the mainpage of a website.27} 28 29echo "Message send successfully \n". This is similar to writing data to a file. 1 <?php 2 3 if(!($sock = socket_create(AF_INET. Hence you can also use the write function to send data to a socket. 8 } 9 10echo "Socket created \n". 6 7 die("Couldn't create socket: [$errorcode] $errormsg \n"). we first connect to an ip address and then send the string message "GET / HTTP/1. 17 } 18 19echo "Connection established \n".125. 0))) 4 { $errorcode = socket_last_error(). 0)) . Later in this tutorial we shall use write function to send data. SOCK_STREAM. Receiving Data Function recv is used to receive data on a socket. 5 $errormsg = socket_strerror($errorcode). its time to receive a reply from the server.1\r\n\r\n". 30 31 32 33 In the above example . 15 16 die("Could not connect: [$errorcode] $errormsg \n"). So lets do it.1\r\n\r\n" to it. Note When sending data to a socket you are basically writing data to that socket. 80)) 13{ 14 $errorcode = socket_last_error(). $message . 11 socket to remote server 12//Connect if(!socket_connect($sock .235. strlen($message) . '74. Now that we have send some data . 20 21$message = "GET / HTTP/1.

google.www. 01-Jan-1990 00:00:00 GMT. 01-Jan-1990 00:00:00 GMT.com Set-Cookie: path=.1 302 Found Location: http://www.google.25{ $errorcode = socket_last_error(). expires=Mon. domain=. expires=Mon.com Set-Cookie: domain=. domain=google.in/ Cache-Control: private Content-Type: text/html. 01-Jan-1990 00:00:00 GMT.com . expires=Mon. path=/. expires=Mon.google. path=/.co.google.com Set-Cookie: expires=. 01-Jan-1990 00:00:00 GMT. 01-Jan-1990 00:00:00 GMT.google. domain=. MSG_WAITALL ) === FALSE) 34if(socket_recv { 35 $errorcode = socket_last_error(). 01-Jan-1990 00:00:00 GMT. path=/. domain=www.com Set-Cookie: path=.php Socket created Connection established Message send successfully HTTP/1. expires=Mon. domain=.www.com Set-Cookie: domain=. domain=google.www.google.com Set-Cookie: expires=. expires=Mon.com Set-Cookie: path=. domain=www. charset=UTF-8 Set-Cookie: expires=.google. 2045 . expires=Mon. domain=www. path=/. domain=google. 01-Jan-1990 00:00:00 GMT. 01-Jan-1990 00:00:00 GMT. 38 39} 40 the received message 41//print echo $buf. $buf . expires=Mon. 01-Jan-1990 00:00:00 GMT. 36 $errormsg = socket_strerror($errorcode). 01-Jan-1990 00:00:00 GMT. 27 28 die("Could not send data: [$errorcode] $errormsg \n"). domain=. 32 33//Now receive reply from server ( $sock . 01-Jan-1990 00:00:00 GMT. path=/. 42 43 44 45 46 47 Here is the output of the above code : 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 $ php /var/www/socket.google. path=/. path=/.google.com Set-Cookie: domain=. path=/. expires=Mon. 29} 30 31echo "Message send successfully \n". expires=Mon. path=/.com Set-Cookie: expires=. path=/. domain=. 26 $errormsg = socket_strerror($errorcode). expires=Mon. 37 die("Could not receive data: [$errorcode] $errormsg \n").com Set-Cookie: path=. path=/.

google.google. 20 Jul 2012 06:39:24 GMT Server: gws Content-Length: 221 X-XSS-Protection: 1. well IT IS html.py?hl=en&answer=151 657 for more info.7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 Set-Cookie: domain=. path=/.com Set-Cookie: NID=62=HZWk5tBSunVEofFri475wbeCNiChGf_bs7Pz_Z32hfm-B0M4JRhzpptjtChOk6lVepLBhOtB2pNHCT5DynobfZaGQaPS5Dh9Rq4YAqt40hExsePHEyA0ECMKj q5KeE.google. </BODY> We can see what reply was send by the server. domain=.com/support/accounts/bin/answer.com.charset=utf-8"> <TITLE>302 Moved</TITLE></HEAD><BODY> <H1>302 Moved</H1> The document has moved <A HREF="http://www." Date: Fri. Quite simple! Now that we have received our reply. It looks something like Html.com replied with the content of the page we requested. domain=. its time to close the socket. expires=Sun. path=/. domain=. Thats it. HttpOnly P3P: CP="This is not a P3P policy! See http://www. 1socket_close($sock). Close socket Function socket_close is used to close the socket.co. mode=block X-Frame-Options: SAMEORIGIN <HTML><HEAD><meta http-equiv="content-type" content="text/html.google.com Set-Cookie: PREF=ID=3c2e53ffcc387bbb:FF=0:TM=1342766363:LM=1342766364:S=DTuSOuahF qyd6vjp. 01-Jan-1990 00:00:00 GMT. . Google. 20-Jul-2014 06:39:24 GMT. path=/. 19-Jan-2013 06:39:24 GMT. expires=Sat.google.in/">here</A>. expires=Mon.

Send some data 4. So the next thing would be to bind it. Listen for incoming connections.com This kind of socket activity represents a CLIENT. 2// = 173. So www. Then the ip address can be used to make a connection using a socket.com is a HTTP Server and your web browser is an HTTP client.google. Quick example 1$ip_address = gethostbyname("www. Get IP address of a hostname/domain When connecting to a remote host . A server is a system that uses sockets to receive incoming connections and provide them with data. 4.Lets Revise So in the above example we learned how to : 1.75. Accept connections 5. Server Programming OK now onto server things.google. Or more technically www. it is necessary to have its IP address. The other kind of socket activity is called a SERVER. Function gethostbyname is used for this purpose. It is just the opposite of Client. 3. Receive a reply Its useful to know that your web browser also does the same thing when you open www.104 So the above code can be used to find the ip address of any domain name.com is a server and your web browser is a client.google. Open a socket 2.194. Bind a socket . Servers basically do the following : 1. It takes the domain name as the parameter and returns the ip address. Bind to a address(and port). Now its time to do some server tasks using sockets. Connect to remote server 3. A client is a system that connects to a remote system to fetch data. Create a socket 2.google.com"). But before we move ahead there are a few side topics that should be covered just incase you need them. Read/Send We have already learnt how to open a socket.

14 $errormsg = socket_strerror($errorcode). Now comes the main part of accepting new connections.Function bind can be used to bind a socket to a particular address and port. 20 Now that bind is done. 1//listen 2socket_listen ($sock . } 17 18 19echo "Socket bind OK \n". . It needs a sockaddr_in structure similar to connect function. 4 $errormsg = socket_strerror($errorcode). There are exceptions to this rule but we shall look into that in some other article.0. We bind a socket to a particular IP address and a certain port number. This will be more clear after checking socket_accept. "127. 15 16 die("Could not bind socket : [$errorcode] $errormsg \n"). Quick example 1 2 if(!($sock = socket_create(AF_INET.1" . 10 11// Bind the source address 12if( !socket_bind($sock. 10) The second parameter of the function socket_listen is called backlog.0. So by specifying 10. For this we need to put the socket in listening mode. Listen for connections After binding a socket to a port the next thing we need to do is listen for connections. its time to make the socket listen to connections. This makes it obvious that you cannot have 2 sockets bound to the same port. Function socket_listen is used to put the socket in listening mode. Just add the following line after bind. then the 11th connection request shall be rejected. By doing this we ensure that all incoming data which is directed towards this port number is received by this application. 5000) ) 13{ $errorcode = socket_last_error(). It controls the number of incoming connections that are kept "waiting" if the program is already busy. 0))) 3 { $errorcode = socket_last_error(). SOCK_STREAM. it means that if 10 connections are already waiting to be processed. 5 6 die("Couldn't create socket: [$errorcode] $errormsg \n"). 7 } 8 9 echo "Socket created \n".

42 43 44 Output . 8 } 9 10 11echo "Socket created \n".. 0))) { 5 $errorcode = socket_last_error(). SOCK_STREAM. \n". 25 26 die("Could not listen on socket : [$errorcode] $errormsg \n"). 12// Bind the source address 13if( !socket_bind($sock.. 6 $errormsg = socket_strerror($errorcode).0. 30 31echo "Waiting for incoming connections.Accept connection Function socket_accept is used for this. 5000) ) 14{ $errorcode = socket_last_error(). $port)) 37{ echo "Client $address : $port is now connected to us. 1 2 3 4 if(!($sock = socket_create(AF_INET. 7 die("Couldn't create socket: [$errorcode] $errormsg \n"). "127. 38 } 39 40socket_close($client). 24 $errormsg = socket_strerror($errorcode).0. 41socket_close($sock).". 32 incoming connection . 34 35//display information about the client who is connected 36if(socket_getpeername($client .1" . $address . 15 $errormsg = socket_strerror($errorcode). 16 17 die("Could not bind socket : [$errorcode] $errormsg \n").This is a blocking call 33//Accept $client = socket_accept($sock). 21 22if(!socket_listen ($sock . 18} 19 20echo "Socket bind OK \n". 27} 28 29echo "Socket listen OK \n". 10)) 23{ $errorcode = socket_last_error().

. Connection closed by foreign host. There are lots of things that can be done after an incoming connection is established.0. So now this program is waiting for incoming connections on port 5000. 6 } 7 . Function socket_write can be used to write something to the socket of the incoming connection and the client should see it. We accepted an incoming connection but closed it immediately.0.1 : 36689 is now connected to us. 4 5 die("Couldn't create socket: [$errorcode] $errormsg \n"). Afterall the connection was established for the purpose of communication. So lets reply to the client.php Socket created Socket bind OK Socket listen OK Waiting for incoming connections. Open a terminal and type $ telnet localhost 5000 It will immediately show $ telnet localhost 5000 Trying 127.0. keep it running. Here is an example : 1 if(!($sock = socket_create(AF_INET.Run the program. So we can see that the client connected to the server.. Escape character is '^]'. And the server output will show Client 127. SOCK_STREAM.. 3 $errormsg = socket_strerror($errorcode). Connected to localhost. This was not very productive.0..1. Try the above steps till you get it working perfect. It should show $ php /var/www/server. We shall use the telnet client for testing this. Now a client can connect to it on this port. Note The socket_getpeername function is used to get details about the client which is connected to the server via a particular socket. 0))) 2 { $errorcode = socket_last_error(). Dont close this program .

22 23 die("Could not listen on socket : [$errorcode] $errormsg \n"). \n". 41 42// Display output back to client 43socket_write($client.1" . . 24} 25 26echo "Socket listen OK \n".8 echo "Socket created \n". 39 40$response = "OK .1..0.. $input". "127. $errormsg = socket_strerror($errorcode). 32 //display information about the client who is connected 33if(socket_getpeername($client . 10)) 20{ $errorcode = socket_last_error().0. And connect to this server using telnet from another terminal and you should see this : 1$ telnet localhost 5000 Trying 127. $port)) 34{ echo "Client $address : $port is now connected to us. 44socket_close($client). 5000) ) 11{ 12 $errorcode = socket_last_error(). 29 30//Accept incoming connection . 27 28echo "Waiting for incoming connections.This is a blocking call 31$client = socket_accept($sock). 21 $errormsg = socket_strerror($errorcode).0. \n". 35 } 36 37 data from the incoming socket 38//read $input = socket_read($client. 2Connected to localhost.. $address . 3Escape character is '^]'. 15 } 16 17echo "Socket bind OK \n". 1024000). 13 14 die("Could not bind socket : [$errorcode] $errormsg \n").0. $response). 45 46 47 48 49 50 Run the above code in 1 terminal... 18 19if(!socket_listen ($sock . 9 10// Bind the source address if( !socket_bind($sock.

0. \n". 9 10// Bind the source address if( !socket_bind($sock. 6 7 So the client(telnet) received a reply from server. 3 $errormsg = socket_strerror($errorcode). Afterall its a server meant to serve. Live Server So a live server will be alive always. 10)) 20{ $errorcode = socket_last_error(). Lets code this up 1 if(!($sock = socket_create(AF_INET. 5000) ) 11{ 12 $errorcode = socket_last_error().4happy 5OK .1" . The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time. 6 } 7 8 echo "Socket created \n". It means that a server is supposed to be running all the time. 22 23 die("Could not listen on socket : [$errorcode] $errormsg \n")... 18 19if(!socket_listen ($sock . SOCK_STREAM. 27 28echo "Waiting for incoming connections. 29 30//start loop to listen for incoming connections . So we need to keep our server RUNNING non-stop. "127. 0))) 2 { $errorcode = socket_last_error(). 15 } 16 17 echo "Socket bind OK \n".google. 21 $errormsg = socket_strerror($errorcode).0. 14 die("Could not bind socket : [$errorcode] $errormsg \n"). happy Connection closed by foreign host. 13 $errormsg = socket_strerror($errorcode). A server like www.com is always up to accept incoming connections. We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. 24 } 25 26echo "Socket listen OK \n". 4 5 die("Couldn't create socket: [$errorcode] $errormsg \n")..

1 : 37123 is now connected to us.1..1 : 37119 is now connected to us. 42 $response = "OK . \n". And the server terminal would show $ php /var/www/server... Client 127..0.. $response).This is a blocking call 33 $client = socket_accept($sock). Escape character is '^]'. happy Connection closed by foreign host. Just put the socket_accept in a loop. 43 44 // Display output back to client 45 socket_write($client. Each of the telnet terminal would show : $ telnet localhost 5000 Trying 127.31while (true) 32{ //Accept incoming connection . and open 3 other terminals. $input".1 : 37122 is now connected to us. 34 35 //display information about the client who is connected if(socket_getpeername($client . Client 127.0.. Connected to localhost. From each of the 3 terminal do a telnet to the server port.0. $port)) 36 { 37 echo "Client $address : $port is now connected to us. .0. 1024000). 38 } 39 40 //read data from the incoming socket 41 $input = socket_read($client.0. Now run the server program in 1 terminal .0.0.php Socket created Socket bind OK Socket listen OK Waiting for incoming connections. $address . happy OK . 46 } 47 48 49 50 51 52 53 We havent done a lot there. Client 127.0.

SOCK_STREAM. $address . Another method is to use the select function. Quick Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 error_reporting(~E_NOTICE). $errormsg = socket_strerror($errorcode). if(!($sock = socket_create(AF_INET. $errormsg = socket_strerror($errorcode). 5000) ) { $errorcode = socket_last_error(). So now its time to handle the connections . $address = "0. after that it does nothing with them. 0))) { $errorcode = socket_last_error(). Handling Connections To handle every connection we need a separate handling code to run along with the main server accepting connections. But still there is not effective communication between the server and the client. The select function basically 'polls' or observers a set of sockets for certain events like if its readable. die("Could not bind socket : [$errorcode] $errormsg \n"). All telnet terminals would show "Connection closed by foreign host. So the select function can be used to monitor multiple clients and check which client has send a message. } echo "Socket bind OK \n". } echo "Socket created \n". Now close the server program. set_time_limit (0). die("Couldn't create socket: [$errorcode] $errormsg \n"). and handle multiple connections together.0. Also it is not able to handle more than 1 connection at a time.0"." Good so far. However php does not support threading directly. or writable or had a problem or not etc. $max_clients = 10.So now the server is running nonstop and the telnet terminals are also connected nonstop. . // Bind the source address if( !socket_bind($sock. $port = 5000. and then the server goes back to accept more connections. One way to achieve this is using threads.0. The main server program accepts a connection and creates a new thread to handle communication for the connection. The server program accepts connections in a loop and just send them a reply.

$i++) { if ($client_socks[$i] == null) { $client_socks[$i] = socket_accept($sock). then a new connection has come in if (in_array($sock. //now add the existing client sockets for ($i = 0. 10)) { $errorcode = socket_last_error(). $except . die("Could not listen on socket : [$errorcode] $errormsg \n"). $read)) { for ($i = 0. //display information about the client who is .. //first socket is the master socket $read[0] = $sock. die("Could not listen on socket : [$errorcode] $errormsg \n"). $write . } } //now call select .. } echo "Socket listen OK \n". $errormsg = socket_strerror($errorcode).blocking call if(socket_select($read . \n". $errormsg = socket_strerror($errorcode).25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 if(!socket_listen ($sock . } //if ready contains the master socket. echo "Waiting for incoming connections. $i++) { if($client_socks[$i] != null) { $read[$i+1] = $client_socks[$i]. null) === false) { $errorcode = socket_last_error(). //array of client sockets $client_socks = array(). $i < $max_clients. //array of sockets to read $read = array(). //start loop to listen for incoming connections and process existing connections while (true) { //prepare array of readable client sockets $read = array(). $i < $max_clients.

84 $message . $i++) 92 { 93 if (in_array($client_socks[$i] . $output). 87 } 88 } 89 } 90 //check each client if they send any data 91 for ($i = 0. $input". $i < $max_clients. 86 break. 95 96 if ($input == null) 97 { 98 //zero length string meaning disconnected. 108 109 //send response to client socket_write($client_socks[$i] . } 80 81 //Send Welcome message to client 82 $message = "Welcome to php socket server version 1.0 83 \n". and i 85 shall reply back \n". $address. $message).. socket_close($client_socks[$i]). 1024). 104 105 $output = "OK . socket_write($client_socks[$i] . 106 107 echo "Sending output to client \n". $read)) 94 { $input = socket_read($client_socks[$i] . 101 } 102 103 $n = trim($input).. \n". remove 99 and close the socket 100 unset($client_socks[$i]).= "Enter a message and press enter.75 connected if(socket_getpeername($client_socks[$i]. 76 $port)) 77 { 78 echo "Client $address : $port is now connected 79 to us. 110 } 111 } 112} 113 114 115 116 117 118 119 120 121 122 .

0..0.0 Enter a message and press enter. Sending output to client Sending output to client The above connection handler takes some input from the client and replies back with the same.. If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.1 : 36274 is now connected to us.1. Sending output to client Sending output to client Client 127..php Socket created Socket bind OK Socket listen OK Waiting for incoming connections.0.1 : 36276 is now connected to us. how are you The server terminal might look like this $ php /var/www/server.1. .0. Connected to 127..0. and i shall reply back hello OK .. You can try out some experiments like writing a chat client or something similar.0. The telnet terminals would show : $ telnet localhost 5000 Trying 127. Sending output to client Sending output to client Client 127. Conclusion By now you must have learned the basics of socket programming in php.1 : 36259 is now connected to us.0.0.. Simple! Here is how the telnet output might look So now we have a server thats communicative. Welcome to php socket server version 1. Thats useful now. Now the server will create a thread for each client connecting to it... hello how are you OK . Client 127. Escape character is '^]'.0.Run the above server and open 3 terminals like before.0.

Sign up to vote on this title
UsefulNot useful