Sending udp message from a remote server to my computer via internet - php

I am trying to send a udp message from a php webpage to my computer and it works if I send it from the localhost, but if I send it from a remote server I will never receive the message. Please advise how to set the ip address, I have public and private ip addresses. I tried $server_ip set to both the public and private ip address of my computer but it doesn't work.
<?php
$server_ip = '127.0.0.1';
$server_port = 2009;
$beat_period = 5;
$message = 'Hello world! ';
print "Sending heartbeat to IP $server_ip, port $server_port\n";
print "press Ctrl-C to stop\n";
if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) {
while (1) {
socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port);
print "Time: " . date("%r") . "\n";
sleep($beat_period);
}
} else {
print("can't create socket\n");
}
?>
Please advise ...

Related

PHP Socket stucking in accept

I have a php socket server and a javascript websocket, but websocket stuck in connecting to socket.
There is no error but websocket stay connecting.
sock.php
set_time_limit(0);
$ip = '127.0.0.1';
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$ret = socket_bind($sock, $ip);
$ret = socket_listen($sock);
do
{
$ref = socket_accept($sock);
/*
Write message
*/
$msg ="Success receive from client\n";
socket_write($ref, $msg, strlen($msg));
/*
Read message
*/
$buf = socket_read($ref , 1024);
echo "Received message: $buf\n";
socket_close($ref);
}while (true);
socket_close($sock);
?>
javascript websocket:
var sock = new WebSocket('ws://localhost/sock.php');
sock.onopen(function()
{
console.log('socket connected.');
});
You must specify the correct port in socket_bind() or it will listen on a random port. You check this with netstat on Linux and Windows. As you try to connect to ws://localhost that should be port 80. However binding to port 80 is usually not allowed, unless you are an admin user. Best to bind to another port, for example 8080, and connect to ws://localhost:8080.

PHP sockets, can't connect - Loop?

Hello i'm trying to learn and build a socket script in PHP this is my code:
Client:
include_once('server.php');
$host = "localhost";
$port = 1025;
$message = "Hello Server";
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
// connect to server
socket_bind($socket, $host);
if (socket_connect($socket, $host, $port) === false) {
echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
else { echo "Connected"; }
Server:
// Variables
$host = "localhost";
$port = 1025;
// No timeout
set_time_limit(0);
// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Can't create socket..");
if ($socket === false) {
echo "Unable to create socket. Error: {$errno} : {$errstr}\n";
die();
}
// Bind Socket
if (socket_bind($socket, $host) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
else { echo "Connected to {$host}:{$port}"; }
// Socket listen
if (socket_listen($socket, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
if (socket_accept($socket) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
// Socket close
socket_close($socket);
But i'm missing something that i cant figure out and i dont know what, When im trying to connect from the client it just loads nothing happens, Can anyone here point me in the right direction and tell me what im doing wrong?
On your client, you do not want socket_bind(). That is for opening up a connection for other systems to connect to; in short, to become a server.
Our client script:
<?php // client.php
$host = "127.0.0.1"; // connect _does_ do DNS lookups, unlike bind, which is mentioned below, but for simplicity of the example I'm explicitly naming the IP address.
$port = 1025;
$message = "Hello Server";
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
// Using die() here because we really don't want to continue on while in an error condition.
die('socket_create() failed: reason: ' . socket_strerror(socket_last_error($socket));
}
// connect to server
if (socket_connect($socket, $host, $port) === false) {
die('socket_connect() failed: reason: ' . socket_strerror(socket_last_error($socket));
}
socket_write($socket, $message);
socket_close($socket);
In your server, you should listen on 0.0.0.0 (or a specific IP address), and not specify a domain name. 0.0.0.0 means to listen to all IP addresses, and any specific IP address means to only listen on the one interface that is configured for that address.
For example, if your server has 2 NICs, one assigned to a public address, say 1.2.3.4, and another assigned to a local address, 192.168.0.2. You also always have your loopback, 127.0.0.1 for free just by having TCP/IP.
If you want to restrict access to your server script to only other hosts on your network, you would set your listen address to 192.169.0.2. Even though your server is accessible through the public IP of 1.2.3.4, this script will simply not listen to any of that traffic.
If you want to restrict access to your server script to only other processes running on that machine, you need to use 127.0.0.1. Using "localhost" will not keep anyone out, because bind does not perform any DNS lookups (and PHP's socket_bind() is only a thin wrapper around the BSD Sockets based system call to bind). It doesn't even look at the hosts file. Thus, any non-IP string will be cast to an integer, usually resulting in it becoming 0, and that 0 will be converted to 0.0.0.0, which will allow access from all interfaces, despite you thinking that you're only listening to localhost traffic.
When you accept a connection, it creates a new socket resource, which I've named $clientSocket in the example below. Don't get confused between the sockets created when a new host connects and your listening socket; they're very similar, but with a very important distinction: When your listening socket has a new message, it is always saying that there is a new host connecting, so you should accept. If it is a client socket, then you'll be using read or recv. (I prefer recv because of the finer control, but I use read in the example below to more clearly show the process rather than adding confusion by having references... which is also why I'm not going to show select.)
Our server script:
<?php //server.php
$listen_address = "0.0.0.0";
$port = 1025;
$maxBuffer = 1024; // bytes, not characters.
// No timeout
//set_time_limit(0); // Shouldn't be necessary in CLI.
// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
die('Unable to create socket: ' . $socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
// Bind Socket
if (socket_bind($socket, $listen_address, $port) === false) {
die('socket_bind() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
else {
echo "Connected to {$listen_address}:{$port}\n";
}
// Accept our client connection
// Typically, this would be where we'd put a loop with socket_select,
// but for our example, since we'll be exiting as soon as we have our
// first packet, we'll listen, accept, read, then close.
if (socket_listen($socket) === false) {
die('socket_listen() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
$clientSocket = socket_accept($socket);
if ($clientSocket === false) {
die('socket_accept() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
// Because the contents of a packet could be longer than our
// buffer size, it's advisable to peek at the socket to see
// if it would block before saying that our message is complete.
// In our example, we're receiving 12 bytes out of our maximum 1024,
// so I leave handling large packets as an exercise for the developer.
$message = socket_read($clientSocket, $maxBuffer);
var_dump($message);
// Socket close
socket_close($clientSocket);
socket_close($socket);
And finally, here's how to run the mess above.
Note that I'm going to have both the server and client run in the same TTY, I'll have the server run as a background process (use the & modifier), but I will not be redirecting their output, so both scripts will be spitting their output into the same terminal.
myhost.mydomain$ php ./server.php &
[8] 76399
Connected to 0.0.0.0:1025
myhost.mydomain$ php ./client.php
string(12) "Hello Server"
[8]+ Done php ./server.php
Your implementation of the server is wrong. Your server should have a loop which is always active listening to connections.
Server
# Create Socket
$socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
# Bind a host and a port to the socket
socket_bind($socket, $host, $port);
# Listen for connection in the socket you just created
socket_listen($socket);
# This is the heart of the server, without it, it can not serve.
while(true)
{
# Accept Client connection if client socket connects
$client = socket_accept($socket);
# Logic #todo Reponse to client
print "Connected." // For testing purposes, see if client actually connected
# Close client connection
socket_close($client);
}
To connect from your client to the server use socket_connect, documentation here.

PHP Socket Programming : Server not accessible from outside network

I am working on PHP socket programming project. In this project we are going to create a service in php socket. This socket will listen on one particular port. And client from outside network will able to communicate on that port.
Till now I am able to create server and client in php for socket programming. Now my pc is connected to LAN so I have to use port forward for connecting my pc with outside client. I forward port 2000 and all communication on that port is transfer to my pc IP address. I have netgear router n150 wireless adsl .I add all configuration on that router. I test port forwarding online at this site http://www.yougetsignal.com/tools/open-ports/ it says port is open.
I test my code on locally (intranet), it is working fine. But when I trying to run server on my pc and client from web server which is my ipage hosting server. It throws me error "Server Could not connect to server".
Server.php
<?php
// set some variables
// My LAN Ip
$host = "192.168.0.5";
$port = 2000;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : " . $input;
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>
Client.php
<?php
//my public ip
$host = "117.223.90.191";
// port on which I port forword
$port = 2000;
$message = "Hello Server";
echo "Message To server :" . $message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :" . $result;
// close socket
socket_close($socket);
?>
Any suggestion for problem. I think many will have same problem like me.
Even if i think the problem is in the lan forwarding, try testing it with :
telnet 117.223.90.191 2000
another thing to try is to make the server listen on all interfaces
$host = "0.0.0.0";
and take a look at http://reactphp.org/

fsocketopen() Not connecting to server?

I've been trying to connect to a Twitch chat via IRC. I've added an echo function to test where I had connected or not as that page was blank and an account didn't join the IRC.
Here is my code:
<?php
set_time_limit(0);
ini_set('display_errors', 'on');
$datatwitch= array(
'server' => 'irc.twitch.tv',
'port' => 6667,
'nick' => 'greatbritishbgbot',
'name' => 'greatbritishbgbot',
'pass' => 'oauth:HERE',
);
?>
<?php
//The server host is the IP or DNS of the IRC server.
$server_host = $datatwitch['server'];
//Server Port, this is the port that the irc server is running on. Deafult: 6667
$server_port = $datatwitch['port'];
//Server Chanel, After connecting to the IRC server this is the channel it will join.
$server_chan = "#greatbritishbg";
//login password
$nickname = $datatwitch['name'];
$nickname_pass = $datatwitch['pass'];
//Ok, We have a nickname, now lets connect.
$server = array(); //we will use an array to store all the server data.
//Open the socket connection to the IRC server
$server['SOCKET'] = #fsockopen($server_host, $server_port, $errno, $errstr, 2);
if($server['SOCKET'])
{
//Ok, we have connected to the server, now we have to send the login commands.
echo "connected";
SendCommand("PASS $nickname_pass \n\r"); //Sends the password not needed for most servers
SendCommand("NICK $nickname\n\r"); //sends the nickname
SendCommand("USER $nickname USING PHP IRC\n\r"); //sends the user must have 4 paramters
while(!feof($server['SOCKET'])) //while we are connected to the server
{
$server['READ_BUFFER'] = fgets($server['SOCKET'], 1024); //get a line of data from the server
echo "[RECIVE] ".$server['READ_BUFFER']."<br>\n\r"; //display the recived data from the server
/*
IRC Sends a "PING" command to the client which must be anwsered with a "PONG"
Or the client gets Disconnected
*/
//Now lets check to see if we have joined the server
if(strpos($server['READ_BUFFER'], "422")) //422 is the message number of the MOTD for the server (The last thing displayed after a successful connection)
{
//If we have joined the server
SendCommand("JOIN $server_chan\n\r"); //Join the chanel
}
if(substr($server['READ_BUFFER'], 0, 6) == "PING :") //If the server has sent the ping command
{
SendCommand("PONG :".substr($server['READ_BUFFER'], 6)."\n\r"); //Reply with pong
//As you can see i dont have it reply with just "PONG"
//It sends PONG and the data recived after the "PING" text on that recived line
//Reason being is some irc servers have a "No Spoof" feature that sends a key after the PING
//Command that must be replied with PONG and the same key sent.
}
flush(); //This flushes the output buffer forcing the text in the while loop to be displayed "On demand"
}
} else {
echo "connection failed";
}
function SendCommand ($cmd)
{
global $server; //Extends our $server array to this function
#fwrite($server['SOCKET'], $cmd, strlen($cmd)); //sends the command to the server
echo "[SEND] $cmd <br>"; //displays it on the screen
}
?>
It appears I can't Get passed if($server['SOCKET']). Is there anyway I can diagnose this? As I have directly connect with the details in hexChat.
The server had actually been preventing me to use fsocket. After contacting my host and moving away from a shared host it started to work.
Please take a look at this answer: https://stackoverflow.com/a/24835967/1163786
Especially:
$socket = fsockopen($bot["Host"], $bot["Port"], $error1, $error2);
if(!$socket) {
echo 'Crap! fsockopen failed. Details: ' . $error1 . ': ' . $error2;
}
To get the details about the socket error = reason for socket not connecting.
Currently, you have $errno, $errstr on fsockopen, but echo only "connection failed".

How to receive web socket message from server in client side by html5 socket api

from couple of days i'm fighting with web sockets. But, yet now i couldn't able to get grip on it.
I manage to build a server side file by PHP which is sending message to a particular address+port. But, when i'm trying to access that message in client side by HTML5 socket api, i can't able to get that.
Here is my server side PHP cile code..
$address = "127.0.0.1";
$service_port = 80;
error_reporting(E_ALL);
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " .
socket_strerror(socket_last_error()) . "\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " .
socket_strerror(socket_last_error($socket)) . "\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.google.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
if(!socket_write($socket, $in, strlen($in)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send message on socket : [$errorcode] $errormsg \n");
}
echo "OK.\n";
In my client side i'm using this following code.
<script type="text/javascript">
// Let us open a web socket
var ws = new WebSocket("ws://127.0.0.1:80/");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
</script>
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo "<br><br>$out<br><br>";
}
socket_close($socket);
But, i can't able to receive the server side message by using this javascript.
This is the first time i'm trying to put my hand in web sockets. SO, i've totally no idea how to do this. I also search a lot in google but can't able to figure out where & what i'm doing wrong.
Regards
It is better to use another port above 1024 because port under 1024 require root privileges, and this port you use it's already for internet services try to use:
$ telnet servername portNumber
Test it under shell or cmd and then you can try to use websocket object.
Its always good practice before connecting to websockets, to check if the browser your user is using supports them....like so....
//First check for firefox, and set it to regular websocket...since Mozilla API is differently named
if (window.MozWebSocket) {
window.WebSocket = window.MozWebSocket;
}
//Then continue with checking
var connection = {};
function connect() {
if(window.WebSocket != undefined) {
if(connection.readyState === undefined || connection.readyState > 1)
{
connection = new WebSocket('ws://127.0.0.1:80');
}
}
}

Categories