Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class m2mp {
- private $m_socket, $m_data = array();
- public function __construct ( $ip, $port, $timeout = 5 )
- {
- // Open the socket
- $this->m_socket = @fsockopen( 'udp://' . $ip, ($port + 1) );
- // Did the socket fail to open?
- if( !$this->m_socket )
- die( 'FAILED TO OPEN UDP SOCKET TO ' . $ip . ':' . $port . '!' );
- // Set the socket timeout time
- @stream_set_timeout( $this->m_socket, $timeout );
- // Store the ip and port
- $this->m_data[ 'ip' ] = $ip;
- $this->m_data[ 'port' ] = $port;
- }
- public function __destruct ( )
- {
- // Close the socket
- @fclose( $this->m_socket );
- // Clear the array data
- unset( $this->m_data );
- }
- private function Unpack ( $data )
- {
- // Set the initial offset
- $offset = 1;
- // Unpack all information from binary data
- $binary = unpack( 'C*', $data );
- // Get the hostname from the data
- $len = $binary[ $offset ];
- $this->m_data[ 'hostname' ] = substr( $data, 0, $len );
- $offset += $len;
- // Get the player count
- $len = ($binary[ $offset ] - 1);
- $this->m_data[ 'playercount' ] = (int)substr( $data, $offset, $len );
- $offset += ($len + 1);
- // Get the max player count
- $len = ($binary[ $offset ] - 1);
- $this->m_data[ 'maxplayers' ] = (int)substr( $data, $offset, $len );
- $offset += ($len + 1);
- // Get the gamemode name
- $len = ($binary[ $offset ] - 1);
- $this->m_data[ 'gamemode' ] = substr( $data, $offset, $len );
- $offset += ($len + 1);
- // Is the server password protected?
- $this->m_data[ 'password' ] = (bool)$binary[ $offset ];
- $offset += 1;
- // Do we have any players in the server?
- if( $this->m_data[ 'playercount' ] > 0 )
- {
- // Create the players array
- $this->m_data[ 'players' ] = array();
- // Loop over all players
- for( $i = 0; $i < $this->m_data[ 'playercount' ]; $i++ )
- {
- // Get the player name
- $len = ($binary[ $offset ] - 1);
- array_push( $this->m_data[ 'players' ], substr( $data, $offset, $len ) );
- $offset += ($len + 1);
- }
- }
- // Is this server summer?
- $this->m_data[ 'summer' ] = (bool)$binary[ $offset ];
- $offset += 1;
- return $this->m_data;
- }
- public function Pulse ( )
- {
- if( !$this->m_socket )
- return false;
- // Query the server
- @fputs( $this->m_socket, 'M2MP' );
- // Did we fail to read any data?
- if( !$result = @fread( $this->m_socket, 1024 ) )
- return false;
- // Is this packet not for m2mp?
- if( $result[0] != 'M' || $result[1] != '2' || $result[2] != 'M' || $result[3] != 'P' )
- return false;
- // Remove the identifier from the string
- $result = substr( $result, 4 );
- // Unpack all the data
- return $this->Unpack( $result );
- }
- };
- ?>
Advertisement
Add Comment
Please, Sign In to add comment