socket_connect() not work with 25 port - php

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.

Related

GameServerQuery how to check if server is online & count online players?

I want to check if a quake3 game server is online or offline. If offline then echo 'Server is offline' if online then echo 'Server is online'.
I'm using this library:
As you see in the library there's already an isOnline function I think that's for server is online or no?! but I don't know how to output that.
Calling the game server data's:
<?php
include 'test/GameServerQuery.php';
$data = GameServerQuery::queryQuake3('1.1.1.1', 28960);
echo 'Hostname: ' . $data['sv_hostname'] . '<br />';
echo 'Players online: ' . $data['sv_maxclients'] . '<br />'; /// How can I count online players / maxclients? ex.: 0/20
echo 'Punkbuster: ' . $data['sv_punkbuster'] . '<br />';
?>
Here is relevant code from the library (in case the link should die or change):
public static function isOnline ($host, $port, $type)
{
if ($type == 'minecraft') { // No need for the full ping
return #fclose (#fsockopen ( $host , $port , $err , $errstr , 2 ));
}
if (method_exists('GameServerQuery', 'query'.$type)) {
return self::{'query'.$type}($host , $port);
}
return #fclose (#fsockopen ( $host , $port , $err , $errstr , 2 ));
}
public static function queryQuake3($host, $port)
{
$reponse = self::ping($host, $port, "\xFF\xFF\xFF\xFFgetstatus\x00");
if ($reponse === false || substr($reponse, 0, 5) !== "\xFF\xFF\xFF\xFFs") {
return false;
}
$reponse = substr($reponse, strpos($reponse, chr(10))+2);
$info = array();
$joueurs = substr($reponse, strpos($reponse,chr(10))+2);
$reponse = substr($reponse, 0, strpos($reponse, chr(10)));
while($reponse != ''){
$info[self::getString($reponse, '\\')] = self::getString($reponse, '\\');
}
if (!empty($joueurs)) {
$info['players'] = array();
while ($joueurs != ''){
$details = self::getString($joueurs, chr(10));
$info['players'][] = array('frag' => self::getString($details, ' '),
'ping' => self::getString($details, ' '),
'name' => $details);
}
}
return $info;
}
private static function ping($host, $port, $command)
{
$socket = #stream_socket_client('udp://'.$host.':'.$port, $errno, $errstr, 2);
if (!$errno && $socket) {
stream_set_timeout($socket, 2);
fwrite($socket, $command);
$buffer = #fread($socket, 1500);
fclose($socket);
return $buffer;
}
return false;
}
private static function getString(&$chaine, $chr = "\x00")
{
$data = strstr($chaine, $chr, true);
$chaine = substr($chaine, strlen($data) + 1);
return $data;
}
It's a static function, just like the one you're already calling. Something like this would do the job, I think:
$result = GameServerQuery::isOnline('1.1.1.1', 28960, "Quake3");
print_r($result);
That will show you what result you get back. I suspect it will be the same as the queryQuake3 function actually, because if you specify "Quake3" as the last parameter, the isOnline function will simply call the "queryQuake3" function and pass the result back directly.
So, the function should return either false if the server is offline or otherwise unresponsive, and either true, or a more complex dataset if it's online.
So in fact I think you could write:
$result = GameServerQuery::isOnline('1.1.1.1', 28960, "Quake3");
if ($result === false) {
echo "Server is offline";
}
else {
echo "Server is online";
}

Socketing C++ to PHP or Android

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

Unable to open socket, connection timed out

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

Ping a minecraft server with javascript (no plugins)?

I'm creating this website which lists minecraft servers. Basically I'm trying to ping all these servers as they are displayed. Solving this problem with php doesn't quite solve it for me, pinging all the servers takes time, and I know javascript can execute multiple "pings" at the same time. How would I do this?
The PHP code I'm using now:
class minecraft_server
{
private $address;
private $port;
public function __construct($address, $port = 25565){
$this->address = $address;
$this->port = $port;
}
public function get_ping_info(&$info){
$starttime = microtime(true);
$socket = #fsockopen($this->address, $this->port, $errno, $errstr, 1.0);
$stoptime = microtime(true);
$ping = round(($stoptime-$starttime)*1000);
if ($socket === false){
return false;
}
fwrite($socket, "\xfe\x01");
$data = fread($socket, 256);
if (substr($data, 0, 1) != "\xff"){
return false;
}
if (substr($data, 3, 5) == "\x00\xa7\x00\x31\x00"){
$data = explode("\x00", mb_convert_encoding(substr($data, 15), 'UTF-8', 'UCS-2'));
}else{
$data = explode('§', mb_convert_encoding(substr($data, 3), 'UTF-8', 'UCS-2'));
}
if (count($data) == 3){
$info = array(
'version' => '1.3.2',
'motd' => $data[0],
'players' => intval($data[1]),
'max_players' => intval($data[2]),
'ping' => $ping
);
}else{
$info = array(
'version' => $data[0],
'motd' => $data[1],
'players' => intval($data[2]),
'max_players' => intval($data[3]),
'ping' => $ping
);
}
return true;
}
}
And you call the function with:
$server = new minecraft_server(IP, PORT);
if (!$server->get_ping_info($info)){
echo "Offline";
}else{
print_r($info);
}
How would I create a similar thing in javascript?
In your place, I probably would have set up a script that, when called, pings the selected server and prints a parse-able result, then call that script using Ajax whenever a ping needs to be sent.

Any STUN/TURN/ICE client library in PHP?

I am trying to establish P2P between two PHP daemon deployed on machines in different network (both behind NAT). I searched around for NAT traversal using PHP on Google and seems like their is no existing solution for this in PHP.
Does anyone know about a solution/library to work this around with PHP?
If anybody else is looking for an answer, here is a simple class that does the job:
<?php
class STUNClient
{
private $socket;
public function __construct()
{
//stun.l.google.com
$this->setServerAddr("66.102.1.127", 19302);
$this->createSocket();
}
public function setServerAddr($host, $port = 3478)
{
$this->serverIP = $host;
$this->serverPort = $port;
}
public function createSocket()
{
$this->socket = socket_create(AF_INET, SOCK_DGRAM, getprotobyname("udp"));
socket_set_nonblock($this->socket);
}
public function getPublicIp()
{
$msg = "\x00\x01\x00\x08\xc0\x0c\xee\x42\x7c\x20\x25\xa3\x3f\x0f\xa1\x7f\xfd\x7f\x00\x00\x00\x03\x00\x04\x00\x00\x00\x00";
$numberOfBytesSent = socket_sendto($this->socket, $msg, strlen($msg), 0, $this->serverIP, $this->serverPort);
$st = time();
while (time() - $st < 1) {
socket_recvfrom($this->socket, $data, 32, 0, $remoteIP, $remotePort);
if (strlen($data) < 32) {
continue;
}
break;
}
try {
$info = unpack("nport/C4s", substr($data, 26, 6));
$ip = sprintf("%u.%u.%u.%u", $info["s1"], $info["s2"], $info["s3"], $info["s4"]);
$port = $info['port'];
return [
'ip' => $ip,
'port' => $port
];
} catch (Exception $e) {
return [
'ip' => "0.0.0.0",
'port' => "0"
];
}
}
}
It's used like this:
$sc = new STUNClient;
print_r( $sc->getPublicIp() ); //prnints out the public ip and port

Categories