Sie sind auf Seite 1von 49

The goal

The goal of the Proxy Rental Application Programming Interface (API) functions is to provide a user the ability to
switch IPs. For that purpose several API calls have to be made in a certain sequence. Below, we describe each
necessary operation, functions used for these operations with their appropriate parameters, while further down,
we provide an example application demonstrating their usage.

Recommended Software

.NET 2.0.4.5 compiler


Microsoft Visual Studio

Add Service Reference

Prior to using ProxyRental APIs, add the following Service Reference to your c# project
http://mprs.proxyrental.net:45679/ProxyRental/SoapClientService

Opening new session


1

A Proxy Rental user can switch IPs multiple times within one session. The actual number of concurrent sessions
depends on the number of licenses purchased from Proxy Rental; one thread per license. However, in order to
accomplish any operation with Proxy Rental APIs a user has to have an open SOAP session.
Private Session session;
...
session = new Session();

The session instantiating line above serves dual purpose. It loads the previous session if it existed. In this case
a user receives the same session id. In the opposite case, a new session is instantiated and a user receives a
new session ID. Therefore a program that uses Proxy rental APIs should save session id so that it can use it as
input parameter in TryRestoreOrLogin method.
session = client.TryRestoreOrLogin(user, session);

method authenticates user on the server and allows subsequent calls to change IPs.
Session type is defined in ProxyRental service reference that should be included in the program.
TryRestoreOrLogin

Client parameter is of SoapClientServiceClienttype and is also defined inProxyRental service reference as is the
user parameter.
User user = newUser();
user.Name = userName;
user.Hash = GetEncryptedString(userPwd);(Please

click this link to see a code sample for this method)

User type has two properties Name and Hash. Name is self-explanatory, while Hash is Encrypted user password.
Each user selects his or her user name and password during ProxyRental Install procedure, prior to login in.

Encryption is provider viaMD5CryptoServicedefined inSystem.Security.CryptographyA sample of encryption function is


provided below in the subsequent example.
In case of success the function session = client.TryRestoreOrLogin(user, session);
returns session id that needs to be supplied to subsequent functions. If this function fails then the function
might return the following error values.
Error Value

Meaning

00000000-0000-0000-0000-000000000000
10000000-0000-0000-0000-000000000000
20000000-0000-0000-0000-000000000000
30000000-0000-0000-0000-000000000000
40000000-0000-0000-0000-000000000000
60000000-0000-0000-0000-000000000000

unknown behavior (example user is not logged in)


user subscription has expired
Number of allowed sessions is exceeded.
incorrect user name or user password
server is under diagnostics
user is locked for 10 mins because of often
sighin/out

Change Proxy
Now, once session is established, a user can start changing IPs. For that purpose one should use Proxy Rental
method ChangeProxy.
ChangeProxyResult changeProxyResult = client.ChangeProxy(session);

method is also defined in ProxyRental service reference. It accepts session parameter, changes IP,
does a number of other internal operations and collects important information that is made available by calling
the following method:
ChangeProxy

GlobalInfo ginfo = client.GetProxyInfo(session, sort);

Global Information
GetProxyInfomethod

accepts two parameters: sessionID and sort, where sort could have two possible values
3

specified in enumerator

GlobalInfoSort

GlobalInfoSort.ByDistance

or
GlobalInfoSort.ByState

Sort order starts matter when user deals with geo-location associated with the new IP and will be discussed
below. When changing ip is the only purpose of the call, thesort parameter can be passed as null.GlobalInfo ginfo =
client.GetProxyInfo(session, null);
GlobalInfo

structure returns the following information:

public class GlobalInfo


{
private GlobalInfo[] nearestInfos;
public stringCurrentIP { get; set; }
public stringCity { get; set; }
public stringCityCode { get; set; }
public stringCountryName { get; set; }
public stringAreaCode { get; set; }
public stringState { get; set; }
public stringLatitude { get; set; }
public stringLongitude { get; set; }
public TimeSpan ProxyTimeout { get; set; }
public intNonDstTimeZone { get; set; }
public longCLTime { get; set; }
public longCLTimeActuality { get; set; }
public stringTimeZoneID { get; set; }
public doublePersistence;
public doubleHealth;
}

Below is the description of those data members that are usually are most useful.

Data Memeber
nearestInfos
AreaCode
City
CityCode
CountryName
CurrentIP
Lattitude
Longitude
State
Persistence

Description
Array containing a list of locations nearest to the Current IP
Area Code of the Current IP
City of the Current IP
Craigs's List City Code (Jake said this is ok, since this wont be accessible to general public)
Country of the current IP
New IP that user gains after switch
Latitude of the Current IP
Longitude of the Current IP
State of the Current IP
Proxy stability 0=unstable and 1=stable

If a current IP isn't located in a CL city, but in its vicinity, then the [city] field also displays the distance to the
nearest CL City

Global Information[] nearestInfos


As stated above, this array contains the information about nearest to the current IPlocations of CL cities. This
information becomes pertinent when an IP happens to be located not in the vicinity of a CL city, but, for
example, in some rural area. In this case, nearestInfosarray provides location information regarding surrounding
CL cities. Latitude and longitude information can be used to determine the distance from the IP location to the
CL city. Please click here for example.
As it was mentioned above, the sort parameter, passed to GetProxyInfo method has two values
GlobalInfoSort.ByDistance and GlobalInfoSort.ByState. Passing ByStatewould sort the city information according to state,
while passing ByDistance would sort the information by distance.

Test Project

The purpose of this project is to illustrate all features mentioned above and offer workable snippets of code.
1. Create New Windows Forms
Application

2. Add Service
Reference to the project

3. Create the following


components on the
form.
1. button [btnYourIP]
2. button [btnNewIP]
3. ListBox
[lbNearestInfo]
4. TextBox [txtCityInfo]
5. TextBox
[txtCityStateZip]
6. TextBox
[txtCurrentIP]
7. TextBox [Lattitude]
8. TextBox [Longitude]
9. TextBox [txtDisplay]

4. Modify Uses Section

5. Get Your IP

The method below will send a request to the webpagehttp://checkip.dyndns.org/ and retrieve the actual IP of your
computer
privatevoid btnYourIP_Click(object sender, EventArgs e)
{
Uri webSiteToCheckYourIP = newUri("http://checkip.dyndns.org/");
// Check your IP by sending a request to the above web site and show a response
IPSite directEndPoint = newIPSite();
directEndPoint.IP = webSiteToCheckYourIP.Host;
directEndPoint.Port = 80;//default http port
try
{
ForwardData(directEndPoint, webSiteToCheckYourIP);

}
Catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//This method forwards the request to the website and receives the response

privatevoidForwardData(IPSite endpoint, Uri website)


{
using (TcpClient tcpClient = newTcpClient())
{
// Connect to forwarding endpoint
tcpClient.Connect(endpoint.IP, endpoint.Port);
using (NetworkStream stream = tcpClient.GetStream())
{
StringBuilder request = newStringBuilder();
request.AppendFormat("GET {0} HTTP1.1\r\n", website.AbsolutePath);
request.AppendFormat("Host: {0}\r\n", website.Host);
request.AppendFormat("Proxy-Rental: {0}\r\n", session.UserSession);
request.AppendLine();
txtDisplay.AppendText("\r\n");
txtDisplay.AppendText(String.Concat("Begin request to {0}-------------\r\n", website.ToString()));
byte[] dataToWrite = Encoding.Default.GetBytes(request.ToString());
// send request to the forwarder
stream.Write(dataToWrite, 0, dataToWrite.Length);
txtDisplay.AppendText("\r\n");
txtDisplay.AppendText(request.ToString());
txtDisplay.AppendText("\r\n");
txtDisplay.AppendText("End request---------------------------------------\r\n");
byte[] dataToRead = newbyte[1000];
txtDisplay.AppendText("\r\n");

10

txtDisplay.AppendText(String.Concat("Begin response from {0}-------------\r\n", website));


do
{
// read response
int read = stream.Read(dataToRead, 0, dataToRead.Length);
string part = Encoding.Default.GetString(dataToRead, 0, read);
txtDisplay.AppendText(part);
} while (stream.DataAvailable);
txtDisplay.AppendText("\r\n");
txtDisplay.AppendText("End response---------------------------------------");
txtDisplay.AppendText("\r\n");
txtDisplay.Refresh();
}
}
}

You can see in the video below that ForwardData method retrieves the actual IP from the
site that belongs to my PC.
https://www.youtube.com/watch?v=O1hSzAfnXTA

11

http://checkip.dyndns.org/

Notice that Proxy-Rental session


ID returns an error code. That is
not surprising, because a user
didnt log in to Proxy Rental, the
session hasnt been initiated
and there no attempt to switch
IP has been made. In fact, the
attempt to display
session.UserSession value inside
ForwardData method only make
sense when ForwardData
method is called after IP was
actually switched.
As it was mentioned above,
ChangeProxy method sets
proxy ,assuming a user was
authenticated, and returns
proxy IP. Then in order to
authenticate a user on the
server PR uses sessionid or if
user IP is static PR uses that ip
itself. The returned IP address
you see below only shows the
actual IP address of the
computer.
12

6. Get New IP
The result would be quite
different if you click the [Get
New IP] button. Notice that
session id has the value that
isn't in the error code table.
Session has been established,
ip switched and you can see
that the IP displayed below is
different from the IP of the
computer.

Below see the code executed by clicking [btnNewIP] button.


First, we create user object by providing a username and encrypting a password. The encryption method would
be offered below. Then session object is created and TryRestoreOrLogin method is called. In this case, as
evident from the picture above, a valid session ID is generated.
Next the program calls ChangeProxy method that switches the IP. To gain the information about the new IP and
13

the corresponding associated information, the program calls GetProxyInfo method. The resulting ginfo structure
provides information that is displayed in the corresponding screen fields in the picture above. The listBox
lbNearestInfo contains additional information about adjacentlocations. It is being populated in the method
fillNearestInfoList, discussed below.
privatevoid btnNewIP_Click(object sender, EventArgs e)
{
try
{
Uri webSiteToCheckYourIP = newUri("http://checkip.dyndns.org/");
// Check your IP directly by sending request to specified web site and showing response
IPSite directEndPoint = newIPSite();
directEndPoint.IP = webSiteToCheckYourIP.Host;
directEndPoint.Port = 80;//default http port
string userName = "fakeuser";//
string userPwd = "fakepwd";

these values should be replaced with the actual user name and password

// Create Proxy Rental service client


using (SoapClientServiceClient client = newSoapClientServiceClient())
{
User user = newUser();
user.Name = userName;
user.Hash = GetEncryptedString(userPwd);
session = newSession();///previous got session
// 1. Authenticate on server side; See server API to parse method result
session = client.TryRestoreOrLogin(user, session);
authenticated = true;
txtDisplay.AppendText(String.Concat("Got sessionID = {0}, userToken = {1}", session.UserSession, session.UserToken));
// 2. Change proxy and get information about forwarding endpoint
ChangeProxyResult changeProxyResult = client.ChangeProxy(session);

14

// 3. if you need Geo information about proxy you have to call below method
GlobalInfoSort globalInfosort = GlobalInfoSort.ByState;
GlobalInfo ginfo = client.GetProxyInfo(session, globalInfosort);
txtDisplay.Clear();
txtDisplay.AppendText(String.Concat("IP: {0}", ginfo.CurrentIP, "\r\n"));
txtDisplay.AppendText(String.Concat("City: {0}", ginfo.City, "\r\n"));
txtDisplay.AppendText(String.Concat("CityCode: {0}", ginfo.CityCode, "\r\n"));
txtCurrentIP.Text = ginfo.CurrentIP;
txtLatitude.Text = ginfo.Latitude;
txtLongitude.Text = ginfo.Longitude;
txtCityStateZip.Text = String.Concat(ginfo.City, " ,", ginfo.State, ", ", ginfo.PostalCode);
lbNearestInfo.DataSource = ginfo.nearestInfos;
lbNearestInfo.DisplayMember = "city";
// 4. Now we can forward traffic through chosen proxy
ForwardData(changeProxyResult.ServerProxy, webSiteToCheckYourIP);
// 5. do logout
authenticated = false;
client.Logout(session);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

To view this process dynamically please see the following short video. https://www.youtube.com/watch?
v=q7NKHemOGDk

7. Encrypt the password


15

To encrypt the password use md5 Encryping Service Provider as shown below.
publicstaticString GetEncryptedString(String str)
{
MD5 md5 = newMD5CryptoServiceProvider();
StringBuilder sb = newStringBuilder(0x20);
foreach (byte b in md5.ComputeHash(Encoding.Default.GetBytes(str ?? String.Empty)))
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}

8. GlobalInfo
This method loops through ginfo.nearestInfos array and unloads all the associated information to a list of local
class IPInfo. Subsequently this list is used as a DataSource for the listBox lbNearestInfo.

The method listed below allows seeing all the associated information for each city in the list. The distance
between the city and the location of IP is calculated by applying a standard distance calculation method
involving both latitudes and longitudes. A sample of this calculation see below in method getDistance.To view
this dynamically please click this linkhttps://www.youtube.com/watch?v=cqJEys6S4OM
privatevoid lbNearestInfo_Click(object sender, EventArgs e)
{
txtCityInfo.Text = "";
GlobalInfo ginfo = (GlobalInfo)lbNearestInfo.Items[lbNearestInfo.SelectedIndex];
txtCityInfo.AppendText(ginfo.City);
txtCityInfo.AppendText("\r\n");
txtCityInfo.AppendText(ginfo.CityCode);
txtCityInfo.AppendText("\r\n");
txtCityInfo.AppendText(ginfo.State);

16

txtCityInfo.AppendText("\r\n");
txtCityInfo.AppendText(ginfo.PostalCode);
txtCityInfo.AppendText("\r\n");
txtCityInfo.AppendText(ginfo.CountryName);
txtCityInfo.AppendText("\r\n");
txtCityInfo.AppendText(ginfo.Longitude);
txtCityInfo.AppendText("\r\n");
txtCityInfo.AppendText(ginfo.Latitude);
txtCityInfo.AppendText("\r\n");
double distance = getDistance(txtLatitude.Text, txtLongitude.Text,ginfo.Latitude, ginfo.Longitude);
txtCityInfo.AppendText(Math.Round(distance,3).ToString());
txtCityInfo.AppendText(" miles");
}
privatedouble getDistance(string lat1, string lon1, string lat2, string lon2)
{
double R = 3956.7657; // Earth radius in miles
double lat1_rad = Convert.ToDouble(lat1) * (Math.PI / 180);
double lat2_rad = Convert.ToDouble(lat2) * (Math.PI / 180);
double sinlat1 = Math.Sin(lat1_rad);
double sinlat2 = Math.Sin(lat2_rad);
double coslat1 = Math.Cos(lat1_rad);
double coslat2 = Math.Cos(lat2_rad);
double dLon = (Convert.ToDouble(lon1) - Convert.ToDouble(lon2)) * (Math.PI / 180);
double cosdLon = Math.Cos(dLon);
double a = sinlat1 * sinlat2 + coslat1 * coslat2 * cosdLon;
double c = Math.Acos(a);
return R * c;
}

17

Just as easily ProxyRental APIs can be called from PHP, ran on Apache server. Below please take a look at the list
of PHP functions that accomplish the same tasks as those called from C# example above.
In the example below, first we will click login button.
Note: Please make sure that you have PHP version is 5.5.11 or later.

The function below implements login logic . User and Password variables are valid user and password
received from Proxy Rental management are set in the program elsewhere. (The entire example code is listed
towards the end of this document) The function authenticates user on a server and re-establishes a session if it
doesn't exist, or creates a new one if it doesn't. The implemented pseudo logic is the same as the one
implemented in c# example above.
/******************************************/
# Login()
#

18

# makes Login request and save sesion vars #


# return bool
#
/******************************************/
public function Login()
{
debug("Login. Start");
if($this->SessionXML)
{
debug("Login. End; Session exist");
return true;
}
$User = new SimpleXMLElement('<User></User>');
$User->addChild('Name',$this->User);
$User->addChild('Hash',$this->Password);
try
{
debug("Login. Request sending: ".rawXML($User->asXML()));
$data=$this->doRequest($User->asXML(),$this->methods['Login']);
debug("Login. Request result: ".rawXML($data));
$Session= new SimpleXMLElement($data);
$this->UserSession=$Session->UserSession;
$this->UserToken=$Session->UserToken;
debug("Login. Parse XML Success, Session: <b>".$this->UserSession."</b>; Token: <b>".$this->UserToken."</b>");
if(in_array($this->UserSession,$this->errors))
{
$this->errorCode = $this->UserSession;
$this->UserSession=false;
$this->Clear();
return false;
}
$this->createSessionXML();
$this->SaveData();
debug("Login. Cookie is set");
}

19

catch(Exception $e)
{
error($e->getMessage());
$this->Clear();
$this->UserSession=false;
return false;
}
debug("Login. End");
return true;
}

Listing for functions


document.

doRequest and SaveData

are located towards the bottom of the in the full example listing

20

21

Notice valid session id highlighted in yellow.


Now, since the session is established we must keep session open and every 30 second invoke method
Synchronize. If this wont be done, server will close automatically and the session along with SessionId and
SessionToken will become invalid.
In this case next login can be active after half an hour. See how its work below.

22

The method executes the following code.


/***************************/
# Synchronize()
#
# makes Synchronize request #
# return bool
#
/***************************/
public function Synchronize()
{
debug("Synchronize. Start");
if(!$this->UserSession)
{
error('Call Login method first');
return false;
}
try
{
debug("Synchronize. Request sending: ".rawXML($this->SessionXML));
$data=$this->doRequest($this->SessionXML,$this->methods['Synchronize']);
debug("Synchronize. Request result: ".rawXML($data));
$Result= new SimpleXMLElement($data);
if($Result->Value=="Ok")
{
return true;
}
else
23

{
return false;
}
}
catch(Exception $e)
{
error($e->getMessage());
$this->Logout();
return false;
}
debug("Synchronize. End");
return true;
}
Now we can change proxy by clicking [Change Proxy] button as below...

The button click method executes the following code.


/***************************/
# ChangeProxy()
#

24

# makes ChangeProxy request #


# return bool
#
/***************************/
public function ChangeProxy()
{
debug("ChangeProxy. Start");
if(!$this->UserSession)
{
error('Call Login method first');
return false;
}
try
{
debug("ChangeProxy. Request sending: ".rawXML($this->SessionXML));
$data=$this->doRequest($this->SessionXML,$this->methods['ChangeProxy']);
debug("ChangeProxy. Request result: ".rawXML($data));
$IPSite= new SimpleXMLElement($data);
$IP=$IPSite->IP;
if(!$IP)
{
error("ChangeProxy. Error request from server");
$this->Logout();
return false;
}
}
catch(Exception $e)
{
error($e->getMessage());
$this->Logout();
return false;
}
$this->ChangeProxy_do=true;
$this->SetValue('ChangeProxyState',$this->ChangeProxy_do);
debug("ChangeProxy. End");

25

return $IPSite;
}

To retrieve the pertinent information related to IP click [Get Global Info] The overall logic is the same as in c#
example.

26

The information stored in GlobalInfo structure formatted as XML. Within one session user can change IP multiple
times. At the end of the session user should log out.

27

The method GetServerProxy returns IP and Port information.


It is essentially a subset of the same information as returned by GlobalInfo.
It has been returning the same information all time until you invoke ChangeProxy.
Therefore this method is usually left for internal use.
Complete PHP Code listing.
<?php
/***************************************/
# ProxyRentalClient for PHP version 1.1 #
# Requirements: PHP5, CURL, SimpleXML #
/***************************************/
/*Page Time out in sec*/
set_time_limit(320);

28

session_start();
/*Log state*/
$isDebug = true;
/**************************************/
# Claas CURL
/*************************************/
class CURL {
function doRequest($method, $url, $vars) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
$data = curl_exec($ch);
curl_close($ch);
if ($data) {
return $data;
} else {
return curl_error($ch);
}
}
function post($url, $vars) {
return $this->doRequest('POST', $url, $vars);
}
}
/**************************************************/
#Class ProxyRentalClient
#
#Public methods:
#
#
ProxyRentalClient(string :$url[optional]) #

29

#
setURL(string:$URL)
#
#
setUser(string:$User)
#
#
setPassword(string:$Password)
#
#
Login()
#
#
Logout()
#
#
Synchronize()
#
#
ChangeProxy()
#
#
GetServerProxy()
#
#
GetGlobalInfo()
#
/**************************************************/
class ProxyRentalClient
{
public $UserSession='';
public $UserToken= '';
public $errorCode;
private $methods = array(
'Login'=>'/Login',
'Logout'=>'/Logout',
'Synchronize'=>'/Synchronize',
'ChangeProxy'=>'/ChangeProxy',
'GetServerProxy'=>'/GetServerProxy',
'GetGlobalInfo'=>'/GetGlobalInfo'
);
private $errors=array(
'00000000-0000-0000-0000-000000000000',
'10000000-0000-0000-0000-000000000000',
'20000000-0000-0000-0000-000000000000',
'30000000-0000-0000-0000-000000000000',
'40000000-0000-0000-0000-000000000000'
);

30

private $URL='';
private $User='';
private $Password='';
private $SessionXML='';
private $ChangeProxy_do=false;
private $verbose = false;

/***********************************************/
# ProxyRentalClient(string :$url[optional])#
# constructor
#
/***********************************************/
public function ProxyRentalClient($url='')
{
if($this->GetData())
{
$this->createSessionXML();
}
$this->setURL($url);
}

/**********************/
# createSessionXML()
# init request session xml

#
#

31

/**********************/
private function createSessionXML()
{
debug("createSessionXML. Start");
$Session = new SimpleXMLElement('<Session></Session>');
$Session->addChild('UserSession',$this->UserSession);
$Session->addChild('UserToken',$this->UserToken);
$this->SessionXML=$Session->asXML();
debug("createSessionXML. End");
}
/**********************/
# SaveData()
#
# set Session and Token to cookies
#
/**********************/
private function SaveData()
{
debug("SaveData");
$this->SetValue('Session',$this->UserSession);
$this->SetValue('Token',$this->UserToken);
$this->SetValue('ChangeProxyState',$this->ChangeProxy_do);
}
private function SetValue($key,$value)
{
$_SESSION[$key] = $value;
setcookie($key,$value);
debug("SetValue. Value Saved; Key: ".$key."; Value: ".$value);
}
/**********************/
# GetData()
# set Session and Token to cookies #
/**********************/
private function GetData(){
debug("GetData: Start");

32

$this->UserSession = $this->GetSavedValue('Session',"");
if($this->UserSession ==""){
debug("GetData, UserSession and UserToken wasn't founded");
return false;
}
$this->UserToken = $this->GetSavedValue('Token',"");
if($this->UserToken ==""){
debug("GetData, UserSession and UserToken wasn't founded");
return false;
}
$this->ChangeProxy_do = $this->GetSavedValue('ChangeProxyState',false);
debug("GetData, UserSession: ".$this->UserSession."; UserToken: ".$this->UserToken);
debug("GetData: End");
return true;
}
private function GetSavedValue($Key, $defaultValue)
{
if(isset($_SESSION[$Key]))
{
debug("GetSavedValue: Server_session Key: ".$Key."; Value: ".$_SESSION[$Key]);
return $_SESSION[$Key];
}
else
{
if(isset($_COOKIE[$Key]))
{
debug("GetSavedValue: Server_COOKIE Key: ".$Key."; Value: ".$_COOKIE[$Key]);
return $_COOKIE[$Key];
}
else
{
debug("GetSavedValue: Key: ".$Key."; default Value: ".$defaultValue);

33

return $defaultValue;
}
}
}
private function Clear()
{
debug("Clear. Start");
$this->SessionXML='';
$this->UserSession = false;
$this->UserToken ='';
$this->ChangeProxyState =false;
unset($_COOKIE['Session']);
unset($_COOKIE['Token']);
unset($_COOKIE['ChangeProxyState']);
setcookie('Session', null, -1, '/');
setcookie('Token', null, -1, '/');
setcookie('ChangeProxyState', null, -1, '/');
unset($_SESSION['Session']);
unset($_SESSION['Token']);
unset($_SESSION['ChangeProxyState']);
debug("Clear. End");
}
/**********************/
# setURL(string:$URL) #
# set servis url
#
/**********************/
public function setURL($URL)
{
$this->URL=$URL;
}

34

/*************************/
# setUser(string:$User) #
# set user name
#
/*************************/
public function setUser($User)
{
$this->User=$User;
}
/**************************************/
# setPassword(string:$Password)
#
# set user password and convert to md5 #
/**************************************/
public function setPassword($Password)
{
$this->Password=md5($Password);
}
/**************************************/
# doRequest(String:$var,String:$method)#
# $var request string
#
# $method servise method
#
/**************************************/
private function doRequest($var,$method='')
{
$curl= new CURL();
$return = $curl->post($this->URL.$method,$var);
if ($this->verbose){
debug("\n--\nRequest: $this->URL$method\n".$var."\nResponse:\n".$return."\n");
}
return $return;

35

}
/******************************************/
# Login()
#
# makes Login request and save sesion vars #
# return bool
#
/******************************************/
public function Login()
{
debug("Login. Start");
if($this->SessionXML)
{
debug("Login. End; Session exist");
return true;
}
$User = new SimpleXMLElement('<User></User>');
$User->addChild('Name',$this->User);
$User->addChild('Hash',$this->Password);
try
{
debug("Login. Request sending: ".rawXML($User->asXML()));
$data=$this->doRequest($User->asXML(),$this->methods['Login']);
debug("Login. Request result: ".rawXML($data));
$Session= new SimpleXMLElement($data);
$this->UserSession=$Session->UserSession;
$this->UserToken=$Session->UserToken;
debug("Login. Parse XML Success, Session: <b>".$this->UserSession."</b>; Token: <b>".$this->UserToken."</b>");
if(in_array($this->UserSession,$this->errors))
{
$this->errorCode = $this->UserSession;
$this->UserSession=false;
$this->Clear();
return false;
}

36

$this->createSessionXML();
$this->SaveData();
debug("Login. Cookie is set");
}
catch(Exception $e)
{
error($e->getMessage());
$this->Clear();
$this->UserSession=false;
return false;
}
debug("Login. End");
return true;
}
/**********************/
# Logout()
#
# makes Logout request #
# return bool
#
/**********************/
public function Logout()
{
debug("Logout. Start");
if(!$this->UserSession)
{
error('Call Login method first');
return false;
}
try
{
debug("Logout. Request sending: ".rawXML($this->SessionXML));
$data=$this->doRequest($this->SessionXML,$this->methods['Logout']);
debug("Logout. Request XML result: ".rawXML($data));

37

$result= new SimpleXMLElement($data);


debug("Logout. Request result: ".$result);
if(!$result)
return false;
}
catch(Exception $e)
{
error($e->getMessage());
return false;
}
$this->Clear();
debug("Logout. End");
return true;
}
/***************************/
# Synchronize()
#
# makes Synchronize request #
# return bool
#
/***************************/
public function Synchronize()
{
debug("Synchronize. Start");
if(!$this->UserSession)
{
error('Call Login method first');
return false;
}
try
{
debug("Synchronize. Request sending: ".rawXML($this->SessionXML));
$data=$this->doRequest($this->SessionXML,$this->methods['Synchronize']);
debug("Synchronize. Request result: ".rawXML($data));
$Result= new SimpleXMLElement($data);

38

if($Result->Value=="Ok")
{
return true;
}
else
{
return false;
}
}
catch(Exception $e)
{
error($e->getMessage());
$this->Logout();
return false;
}
debug("Synchronize. End");
return true;
}
/***************************/
# ChangeProxy()
#
# makes ChangeProxy request #
# return bool
#
/***************************/
public function ChangeProxy()
{
debug("ChangeProxy. Start");
if(!$this->UserSession)
{
error('Call Login method first');
return false;
}
try
{

39

debug("ChangeProxy. Request sending: ".rawXML($this->SessionXML));


$data=$this->doRequest($this->SessionXML,$this->methods['ChangeProxy']);
debug("ChangeProxy. Request result: ".rawXML($data));
$IPSite= new SimpleXMLElement($data);
$IP=$IPSite->IP;
if(!$IP)
{
error("ChangeProxy. Error request from server");
$this->Logout();
return false;
}
}
catch(Exception $e)
{
error($e->getMessage());
$this->Logout();
return false;
}
$this->ChangeProxy_do=true;
$this->SetValue('ChangeProxyState',$this->ChangeProxy_do);
debug("ChangeProxy. End");
return $IPSite;
}
/******************************/
# GetServerProxy()
#
# makes GetServerProxy request #
# return SimpleXML Object
#
/******************************/
public function GetServerProxy()
{
debug("GetServerProxy. Start");
if(!$this->UserSession)
{
error('Call Login method first');

40

return false;
}
try
{
debug("GetServerProxy. Request sending: ".rawXML($this->SessionXML));
$data=$this->doRequest($this->SessionXML,$this->methods['GetServerProxy']);
debug("GetServerProxy. Request result: ".rawXML($data));
$Server= new SimpleXMLElement($data);
$IP=$Server->IP;
if(!$IP)
{
error("ChangeProxy. Error request from server");
$this->Logout();
return false;
}
if($IP=='')
{
error("ChangeProxy. IP and Port wasn't taken");
$Server = $this->ChangeProxy();
//$this->Logout();
//return false;
}
debug("GetServerProxy. Parse XML Success, Server: <b>".$Server."</b>");
}
catch(Exception $e)
{
error($e->getMessage());
$this->Logout();
return false;
}
debug("GetServerProxy. End");
return $Server;
}

41

/******************************/
# GetGlobalInfo()
#
# makes GetGlobalInfo request #
# return SimpleXML Object
#
/******************************/
public function GetGlobalInfo()
{
debug("GetGlobalInfo. Start");
if(!$this->UserSession)
{
error('Call Login method first');
return false;
}
if(!$this->ChangeProxy_do)
{
error('Call ChangeProxy method first');
return false;
}
try
{
debug("GetGlobalInfo. Request sending: ".rawXML($this->SessionXML));
$data=$this->doRequest($this->SessionXML,$this->methods['GetGlobalInfo']);
debug("GetGlobalInfo. Request result: ".rawXML($data));
$GetGlobalInfo= new SimpleXMLElement($data);
debug("GetServerProxy. Parse XML Success, GlobalInfo: <b>".$GetGlobalInfo."</b>");
}
catch(Exception $e)
{
error($e->getMessage());
$this->Logout();
return false;
}
debug("GetGlobalInfo. End");
return $GetGlobalInfo;

42

}
function setVerboseMode($mode){
$this->verbose = (bool)$mode;
}
}
$message ='';
function rawXML($xml)
{
return "<pre>".htmlentities($xml)."</pre>";
}
function message($text, $type)
{
global $message;
//$message.= "<i>".date("Y-m-d H:i:s")."</i> <b>".$type.":</b> ".$text."<br/>";
echo "<i>".date("Y-m-d H:i:s")."</i> <b>".$type.":</b> ".$text."<br/>";
}
function debug($text)
{
global $isDebug;
if($isDebug){
message($text,"info");
}
}
function error($text)
{
message($text,"error");
message(debug_print_backtrace()."<br/>","error");
}
function InitProxyRentalClient()

43

{
$ProxyRentalClient=new ProxyRentalClient();
$ProxyRentalClient->setURL('http://mprs.proxyrental.net:45679/ProxyRental/SoapClientService');
$ProxyRentalClient->setUser('aaaaaaa'); // here you enter your actual username and password
$ProxyRentalClient->setPassword('bbbbbb');
$ProxyRentalClient->setVerboseMode(false);
return $ProxyRentalClient;
}
function GetIPAndPort($value)
{
return "<b>".$value->IP.":".$value->Port."</b>";
}

/******************************************************example*********************************************************/
$IPResult = '';
debug($_SERVER['REQUEST_METHOD']);
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(!isset($_POST['method']))
exit();
$method = $_POST['method'];
switch($method)
{
case "Synchronize":
$ProxyRentalClient = InitProxyRentalClient();
echo 'Synchronize result: '.($ProxyRentalClient->Synchronize()?"True":"False");
break;
case "GetServerProxy":
$ProxyRentalClient = InitProxyRentalClient();
$Server = $ProxyRentalClient->GetServerProxy();
echo GetIPAndPort($Server);

44

break;
case "ChangeProxy":
$ProxyRentalClient = InitProxyRentalClient();
$Server = $ProxyRentalClient->ChangeProxy();
echo GetIPAndPort($Server);
break;
case "GetGlobalInfo":
$ProxyRentalClient = InitProxyRentalClient();
echo $ProxyRentalClient->GetGlobalInfo();
break;
case "Login":
$ProxyRentalClient = InitProxyRentalClient();
echo "Login result: ".(($ProxyRentalClient->Login())?"True":"False");
break;
case "Logout":
$ProxyRentalClient = InitProxyRentalClient();
echo "Logout result: ".(($ProxyRentalClient->Logout())?"True":"False");
break;
default:
echo 'Fail';
break;
}
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Proxy Example</title>
<style type="text/css">
pre{
margin-top:5px;
margin-bottom: 0;

45

}
.buttons{
}
.buttons ul li{
overflow:hidden;
}
.buttons ul li strong{
float:left;
padding: 0 0 3px 20px;
}
.buttons ul li span{
display: block;
float: none;
width: auto;
margin: 0 0 0 40%;
}
.fieldlimit{
background: none repeat scroll 0 0 #b9c0c8;
box-shadow: 0 -1px #2a2a2a;
float: left;
height: 1px;
margin-bottom: 10px;
width:100%;
}
footer{
font-style: italic;
text-align: center;

46

}
#ip{
font-weight:bold;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
//Start timer for keeping session token activity
Timer(function(){
$.post( "getProxy.php", { method: "Synchronize"},function(result){
$('#SyncResult').html(result);
});
return true;
},30000);
$('#ChangeProxy').click(function(){
$.post( "getProxy.php", { method: "ChangeProxy"},function(result){
$('#ChangeProxyResult').html(result);
});
});
$('#GetGlobalInfo').click(function(){
$.post( "getProxy.php", { method: "GetGlobalInfo"},function(result){
$('#GetGlobalInfoResult').html(result);
});
});
$('#GetServerProxy').click(function(){
$.post( "getProxy.php", { method: "GetServerProxy"},function(result){
$('#GetServerProxyResult').html(result);
});

47

});
$('#Login').click(function(){
$.post( "getProxy.php", { method: "Login"},function(result){
$('#LoginResult').html(result);
});
});
$('#Logout').click(function(){
$.post( "getProxy.php", { method: "Logout"},function(result){
$('#LogoutResult').html(result);
});
});
});
function Timer(func, interval) {
if (func == undefined)
return false;
setTimeout(function () {
var res = true;
try {
res = func();
}
catch (ex) {
console.debug("Timer func:", ex);
}
if (res)
Timer(func, interval);
}, interval);
return true;
}
</script>
</head>
<body>

48

<div
<div
<div
<div

class="fieldlimit"> </div>
id="ip"><?php echo $IPResult; ?></div>
id="SyncResult"></div>
class="buttons">
<ul>
<li>
<strong><button id="Login">Login</button></strong>
<span id="LoginResult">???</span>
</li>
<li>
<strong><button id="Logout">Logout</button></strong>
<span id="LogoutResult">???</span>
</li>
<li>
<strong><button id="ChangeProxy">Change Proxy</button></strong>
<span id="ChangeProxyResult">???</span>
</li>
<li>
<strong><button id="GetGlobalInfo">Get Global Info</button></strong>
<span id="GetGlobalInfoResult">???</span>
</li>
<li>
<strong><button id="GetServerProxy">Get Server Proxy</button></strong>
<span id="GetServerProxyResult">???</span>
</li>
</ul>
</div>
</body>
</html>

49

Das könnte Ihnen auch gefallen