I'd like to connect to my c++ server using php...
So far, i got:
Server.cpp
#include <winsock2.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
WSADATA wsaData;
SOCKET mySocket;
SOCKET myBackup;
SOCKET acceptSocket;
sockaddr_in myAddress;
// setup WSA and socket....
if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
{
cerr<<"Socket Initialization: Error with WSAStartup\n";
system("pause");
WSACleanup();
exit(10);
}
//Create a socket
mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( mySocket == INVALID_SOCKET )
{
cerr<<"Socket Initialization: Error creating socket"<<endl;
system("pause");
WSACleanup();
exit(11);
}
myBackup = mySocket;
//bind
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( "0.0.0.0" );
myAddress.sin_port = htons( 25555 );
if ( bind ( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress) ) == SOCKET_ERROR )
{
cerr<<"ServerSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(14);
}
//listen
if ( listen ( mySocket, 10 ) == SOCKET_ERROR )
{
cout<<"ERR: ServerSocket: Error listening on socket\n";
system("pause");
WSACleanup();
exit(15);
}
cout<<"srv started. listeninig...\n";
//accept
acceptSocket = accept( myBackup, NULL, NULL );
while ( acceptSocket == SOCKET_ERROR )
{
acceptSocket = accept( myBackup, NULL, NULL );
}
mySocket = acceptSocket;
cout<<"done.\n";
return 0;
}
and the php client
<?php
$port = 25555;
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
#socket_bind($socket,'',$port);
socket_connect($socket, '/my_ip/', $port);
echo 'connecting...';
?>
I dont know what to do. the c++ server just cant see php client...
You need the correct checks in PHP to make sure everything worked.
Try this:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
die("socket_create() failed: Reason: " . socket_strerror(socket_last_error()) . "\n\n");
return false;
}
echo("Attempting to connect to '{$IP}' on port '{$PORT}'");
$result = socket_connect($socket, $IP, $PORT);
if ($result === false) {
echo("socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n\n");
return false;
} else {
echo "OK.\n\n";
}
check error codes...
socket_create
socket_create() returns a socket resource on success, or FALSE on error.
and
socket_connect
Returns TRUE on success or FALSE on failure.
The error code can be retrieved with socket_last_error().
This code may be passed to socket_strerror() to get a textual explanation of the error.
Related
I have a server hosted on ipaddress:8728. I can access it's service perfectly using my Java Client program. Now I am trying to access this service from my codeigniter web app hosted on the web using stream_socket_client(). But it returns Error 111(Connection Refused). Then I moved my server to port 80(ipaddress:80) and stream_socket_client program is working fine. Why does stream socket client fails to fetch data from from server on port other than port 80 and when my java socket client is working perfectly fine.
Bellow is my PHP code.
public function connect($ip, $login, $password)
{
for ($ATTEMPT = 1; $ATTEMPT <= $this->attempts; $ATTEMPT++) {
$this->connected = false;
$PROTOCOL = ($this->ssl ? 'ssl://' : '' );
$context = stream_context_create(array('ssl' => array('ciphers' => 'ADH:ALL', 'verify_peer' => false, 'verify_peer_name' => false)));
$this->debug('Connection attempt #' . $ATTEMPT . ' to ' . $PROTOCOL . $ip . ':' . $this->port . '...');
$this->socket = #stream_socket_client($PROTOCOL . $ip.':'. $this->port, $this->error_no, $this->error_str, $this->timeout, STREAM_CLIENT_CONNECT,$context);//this line has exception
if ($this->socket) {
echo "\nSocket is not null";
socket_set_timeout($this->socket, $this->timeout);
$this->write('/login', false);
$this->write('=name=' . $login, false);
$this->write('=password=' . $password);
$RESPONSE = $this->read(false);
if (isset($RESPONSE[0])) {
if ($RESPONSE[0] == '!done') {
if (!isset($RESPONSE[1])) {
// Login method post-v6.43
$this->connected = true;
break;
} else {
// Login method pre-v6.43
$MATCHES = array();
if (preg_match_all('/[^=]+/i', $RESPONSE[1], $MATCHES)) {
if ($MATCHES[0][0] == 'ret' && strlen($MATCHES[0][1]) == 32) {
$this->write('/login', false);
$this->write('=name=' . $login, false);
$this->write('=response=00' . md5(chr(0) . $password . pack('H*', $MATCHES[0][1])));
$RESPONSE = $this->read(false);
if (isset($RESPONSE[0]) && $RESPONSE[0] == '!done') {
$this->connected = true;
break;
}
}
}
}
}
}
fclose($this->socket);
}else{
echo "||\nError no = ".$this->error_no."||";
echo "||\n Error Message = ".$this->error_str."||";
echo "||\nsocket is null||";
}
sleep($this->delay);
}
if ($this->connected) {
$this->debug('Connected...');
} else {
$this->debug('Error...');
}
return $this->connected;
}
Is it happening for mistake in my code? or some protective feature on the server where web app is hosted?
I have code for client - server. Server code use C++ with local port and the client i wanna make use PHP or Android. But I dont't know how to make the code.
NB :
Server App use local port 10001
My code server like this (networkex.cpp)
bool CNetworkEX::LoginStatRequest(int n, char* pMsg)
{
_login_server_stat_request_aclo* pRecv = (_login_server_stat_request_aclo*)pMsg;
_login_server_stat_result_loac Send;
Send.wClientIndex = pRecv->wClientIndex;
if ( pRecv->byStat == 0 )
{
}
else if ( pRecv->byStat == 1 )
{
g_Main.m_bExternalOpen = true;
::StringOutput("Connection External Open");
}
else if ( pRecv->byStat == 2 )
{
g_Main.m_bExternalOpen = false;
::StringOutput("Connection External Close");
}
if ( g_Main.m_bExternalOpen )
Send.byRet = 1;
else
Send.byRet = 2;
BYTE byType[msg_header_num] = {system_msg, login_server_stat_result_loac};
m_pProcess[LINE_ACCOUNT]->LoadSendMsg(0, byType, (char*)&Send, Send.size());
return true;
}
My main (mainthread.cpp)
bool CMainThread::CommandProcess(char* pszCmd)
{
int nWordNum = ::ParsingCommand(pszCmd, max_cheat_word, s_pszDstCheat, max_cheat_word_size);
if(nWordNum <= 0)
return false;
if(!strcmp("/open", s_pszDstCheat[0]))
{
::StringOutput("Connection External Open");
m_bExternalOpen = true;
return true;
}
else if(!strcmp("/close", s_pszDstCheat[0]))
{
::StringOutput("Connection External Close");
m_bExternalOpen = false;
return true;
}
else if(!strcmp("/patchup", s_pszDstCheat[0]))
{
DWORD dwBufNum = m_dwPatchServerNum + 1;
if(dwBufNum > MAX_PATCHER_PER_GLOBAL)
dwBufNum = MAX_PATCHER_PER_GLOBAL;
::StringOutput("Patch Server increases(%d -> %d)", m_dwPatchServerNum, dwBufNum);
m_dwPatchServerNum = dwBufNum;
return true;
}
else if(!strcmp("/patchdown", s_pszDstCheat[0]))
{
DWORD dwBufNum;
if(m_dwPatchServerNum <= 1)
dwBufNum = 1;
else
dwBufNum = m_dwPatchServerNum - 1;
::StringOutput("Patch Server decreases(%d -> %d)", m_dwPatchServerNum, dwBufNum);
m_dwPatchServerNum = dwBufNum;
return true;
}
else if(!strcmp("/예약", s_pszDstCheat[0]))
{
if(nWordNum > 1)
{
if(!strcmp("The outer block", s_pszDstCheat[1]) && nWordNum == 7)
{
if(_SetReserveExternalClose(atoi(s_pszDstCheat[2]), atoi(s_pszDstCheat[3]), atoi(s_pszDstCheat[4]), atoi(s_pszDstCheat[5]), atoi(s_pszDstCheat[6])))
::StringOutput("Reservations accepted");
else
::StringOutput("Booking time errors");
return true;
}
}
}
else if(!strcmp("/loginstat", s_pszDstCheat[0]))
{
if ( m_bExternalOpen )
::StringOutput("External access status");
else
::StringOutput("External connection error status");
return true;
}
else if(!strcmp("/clientcount", s_pszDstCheat[0]))
{
DWORD dwClientCount = CountAliveConnection();
::StringOutput( "Connection : %d", dwClientCount );
return true;
}
return false;
}
I wanna my client just send the message like "/open" or "close" but i don't know hot to write the code in php or android. anyone can help me to solve my problem?
Edit
I already try use this php code
<?php
$host = "127.0.0.1";
$port = 10001;
$message = "open";
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);
?>
and the respon in my browser like this http://prntscr.com/dqje54 and in my server app not recieve the message /open
I try to write code for email verify like that
But i have one problem, 25 port not connect with any mail server
My code like that
Example.php
<?php
require('smtp-validate-email.php');
$from = 'harsukh21#gmail.com'; // for SMTP FROM:<> command
$emails = 'harsukh#gmail.com';
$validator = new SMTP_Validate_Email($emails, $from);
$smtp_results = $validator->validate();
echo "<pre>";print_r($smtp_results);exit;
smtp-validate-email.php
<?php/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of EmailValidation * * #author Harsukh Makwana <harsukh21#gmail.com> */class EmailValidation{ public $hellodomain = 'itsolutionstuff.com'; public $mailfrom = 'harsukh21#gmail.com'; public $rcptto; public $mx; public $ip; public function __construct() { $this->ip = '192.168.2.14'; } public function checkEmail($email = null) { $this->rcptto = $email; $array = explode('#', $this->rcptto); $dom = $array[1]; if (getmxrr($dom, $mx)) { $this->mx = $mx[rand(0, count($mx) - 1)]; return $this->processRange($this->ip); } return false; } private function asyncRead($sock) { $read_sock = array($sock); $write_sock = NULL; $except_sock = NULL; if (socket_select($read_sock, $write_sock, $except_sock, 5) != 1) { return FALSE; } $ret = socket_read($sock, 512); return $ret; } private function smtpConnect($mta, $src_ip) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($sock == FALSE) { return array(FALSE, 'unable to open socket'); } if (!socket_bind($sock, $src_ip)) { return array(FALSE, 'unable to bind to src ip'); } $timeout = array('sec' => 10, 'usec' => 0); socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, $timeout); socket_set_nonblock($sock); var_dump(#socket_connect($sock, $mta, 25));exit; #socket_connect($sock, $mta, 25); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'inital read timed out'); } if (!preg_match('/^220/', $ret)) { // Not a good connection. return array(FALSE, $ret); } // Now do the EHLO. socket_write($sock, "HELO ".$this->hellodomain."\r\n"); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'ehlo timed out'); } if (!preg_match('/^250/', $ret)) { // Not a good response. return array(FALSE, $ret); } // Now MAIL FROM. socket_write($sock, "MAIL FROM:<".$this->mailfrom.">\r\n"); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'from timed out'); } if (!preg_match('/^250/', $ret)) // Not a good response. return array(FALSE, $ret); // Now RCPT TO. socket_write($sock, "RCPT TO:<".$this->rcptto.">\r\n"); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'rcpt to timed out'); } if (!preg_match('/^250/', $ret)) { // Not a good response. return array(FALSE, $ret); } // All good. socket_close($sock); return array(true, $ret); } private function processRange($ip) { list($ret, $msg) = $this->smtpConnect($this->mx, $ip); $msg = trim($msg); return $ret; }}
Output
Array
(
[harsukh#gmail.com] =>
[domains] => Array
(
[gmail.com] => Array
(
[users] => Array
(
[0] => harsukh
)
[mxs] => Array
(
[gmail-smtp-in.l.google.com] => 5
[alt1.gmail-smtp-in.l.google.com] => 10
[alt2.gmail-smtp-in.l.google.com] => 20
[alt3.gmail-smtp-in.l.google.com] => 30
[alt4.gmail-smtp-in.l.google.com] => 40
[gmail.com] => 0
)
)
)
)
Here harsukh#gmail.com is a already exist, But i getting null responce
can i use another port for mail server?
You can't use a port that's already in use. So probebly there is already an email server on the same machine where you are running your code.
can i use another port for mail server?
If you plan to use only clients written by yourself, so that you can change the port to which they send data, that can be acceptable, otherwise no.
Trying to sent packages from my webhost to a game server, using this code. However it always results in Unable to open socket: Connection timed out (110) ad I can't figure out why it times out. When I try this on my localhost, it works perfectly but when on webhost, it just times out. I've tried to set the timeout to something else but it didn't help.
define("SERVERDATA_EXECCOMMAND",2);
define("SERVERDATA_AUTH",3);
class RCon {
var $Password;
var $Host;
var $Port = 27015;
var $_Sock = null;
var $_Id = 0;
function RCon ($Host,$Port,$Password) {
$this->Password = $Password;
$this->Host = $Host;
$this->Port = $Port;
$this->_Sock = #fsockopen($this->Host,$this->Port, $errno, $errstr, 30) or
die("Unable to open socket: $errstr ($errno)\n");
$this->_Set_Timeout($this->_Sock,2,500);
}
function Auth () {
$PackID = $this->_Write(SERVERDATA_AUTH,$this->Password);
// Real response (id: -1 = failure)
$ret = $this->_PacketRead();
if ($ret[1]['id'] == -1) {
die("Authentication Failure\n");
}
}
function _Set_Timeout(&$res,$s,$m=0) {
if (version_compare(phpversion(),'4.3.0','<')) {
return socket_set_timeout($res,$s,$m);
}
return stream_set_timeout($res,$s,$m);
}
function _Write($cmd, $s1='', $s2='') {
// Get and increment the packet id
$id = ++$this->_Id;
// Put our packet together
$data = pack("VV",$id,$cmd).$s1.chr(0).$s2.chr(0);
// Prefix the packet size
$data = pack("V",strlen($data)).$data;
// Send packet
fwrite($this->_Sock,$data,strlen($data));
// In case we want it later we'll return the packet id
return $id;
}
function _PacketRead() {
//Declare the return array
$retarray = array();
//Fetch the packet size
while ($size = #fread($this->_Sock,4)) {
$size = unpack('V1Size',$size);
//Work around valve breaking the protocol
if ($size["Size"] > 4096) {
//pad with 8 nulls
$packet = "\x00\x00\x00\x00\x00\x00\x00\x00".fread($this->_Sock,4096);
} else {
//Read the packet back
$packet = fread($this->_Sock,$size["Size"]);
}
array_push($retarray,unpack("V1ID/V1Response/a*S1/a*S2",$packet));
}
return $retarray;
}
function Read() {
$Packets = $this->_PacketRead();
foreach($Packets as $pack) {
if (isset($ret[$pack['ID']])) {
$ret[$pack['ID']]['S1'] .= $pack['S1'];
$ret[$pack['ID']]['S2'] .= $pack['S1'];
} else {
$ret[$pack['ID']] = array(
'Response' => $pack['Response'],
'S1' => $pack['S1'],
'S2' => $pack['S2'],
);
}
}
return $ret;
}
function sendCommand($Command) {
$Command = '"'.trim(str_replace(' ','" "', $Command)).'"';
$this->_Write(SERVERDATA_EXECCOMMAND,$Command,'');
}
function rconCommand($Command) {
$this->sendcommand($Command);
$ret = $this->Read();
//ATM: Source servers don't return the request id, but if they fix this the code below should read as
// return $ret[$this->_Id]['S1'];
return $ret[0]['S1'];
}
}
If I specify udp connection in fsockopen it does not timeout, however if I try tcp, it times out. Most likely caused by the host, but I have no idea where to go from this.
https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
https://developer.valvesoftware.com/wiki/Server_queries
I need print a DataMatrix with Carrier Return and Line Feed.
My printer its a Zebra GK420t.
I make the label in Zebra Designer and when the label is printed from Zebra Designer the CR and LF works, but when i export the label to a PRN file, to print with PHP, the CR and LF not working.
PHP Code
<?php
class ZebraBarcode {
var $host = "";
var $port = "";
var $error = "";
var $prn = "";
function __construct($host,$port) {
$this->host = $host;
$this->port = $port;
$this->prn = "CT~~CD,~CC^~CT~
^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD30^JUS^LRN^CI0^XZ
^XA
^MMT
^PW799
^LL0400
^LS0
^FO4,4^GB795,396,8^FS
^FO5,197^GB794,101,8^FS
^FT642,236^A0N,25,26^FH\^FDCANTIDAD^FS
^FT275,67^A0N,37,52^FH\^FDMEMORIA GRABADA^FS
^FT587,328^A0N,28,28^FH\^FDLOTE^FS
^FT355,328^A0N,28,28^FH\^FDPANEL^FS
^FT22,329^A0N,28,28^FH\^FDMODELO^FS
^FT30,236^A0N,25,26^FH\^FDSEMIELABORADO^FS
^FT34,122^A0B,25,24^FH\^FDEBS^FS
^FT34,277^A0N,34,33^FH\^FD4-651-IAPOWTV00148^FS
^FT587,381^A0N,39,38^FH\^FDL104^FS
^FT355,380^A0N,39,38^FH\^FDHIR^FS
^FT21,381^A0N,39,38^FH\^FD32LD846HT^FS
^FT294,165^A0N,90,88^FH\^FDOP-84366^FS
^FT613,283^A0N,42,69^FH\^FD99000^FS
^BY160,160^FT53,187^BXN,5,200,0,0,1,_
^FH\^FDOP-84188\0D\0A4-651-IAPOWTV00148\0D\0APLA\0D\0A99000\0D\0A100\0D\0AP3-UshZebra3^FS
^FO15,333^GB773,0,6^FS
^FO575,299^GB0,92,4^FS
^FO344,299^GB0,92,4^FS
^LRY^FO593,208^GB0,79,7^FS^LRN
^LRY^FO582,300^GB206,0,31^FS^LRN
^LRY^FO351,300^GB222,0,32^FS^LRN
^LRY^FO602,208^GB185,0,34^FS^LRN
^LRY^FO16,300^GB325,0,32^FS^LRN
^LRY^FO264,26^GB470,0,54^FS^LRN
^LRY^FO17,208^GB222,0,34^FS^LRN
^LRY^FO14,14^GB0,180,23^FS^LRN
^PQ1,0,1,Y^XZ
";
}
function Imprimir(){
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
$this->error = "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
return false;
}
$result = socket_connect($socket, $this->host, $this->port);
if ($result === false) {
$this->error = "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
return false;
}
socket_write($socket, $this->prn, strlen($this->prn));
socket_close($socket);
return true;
}
}
$o = new ZebraBarcode("10.30.30.128",9100);
$o->Imprimir();
?>
The code works!!,but CR and LF still not working. Any ideas?
Thanks in advance!
Hex values normally are escaped with an _ (underscore).
Try _0D_0A instead of \0D\0A!