Asudahlah.com

Programming, tutorials, mechatronics, operating systems, and other tech stuff

PHPExcel Generate Excel Spreadsheet Files in PHP with Different Formats

71 comments
PHPExcel is a powerful PHP library (class) which allows us to generate and read Excel spreadsheet file in PHP server-side. Developed by PHPOffice team.

Depending on the circumstances, generating an excel spreadsheet file as a reporting medium is a great way to present reporting data in offline, independent manner. Especially when dealing about printing and lots of numeric data such as financial report.

Reading an excel file using PHP is also a good way to automate data entry. Especially when dealing with batch data entries. And on the end-user side, this method will also ease the user as the interface for entering the data is an excel spreadsheet file which most people are familiar with. And absolutely more agile when compared to web-interfaced forms.

To use this library, simply download the library files here.

Extract it anywhere in your web root directories. Call the PHPExcel.php file in your script and you're good to go.

Here's a Hello World PHP script example to generate an excel file.
I think the comments in pretty self-explanatory.
<?php
require_once 'Classes/PHPExcel.php';

//create PHPExcel object
$excel = new PHPExcel();

//insert some data to PHPExcel object
$excel->setActiveSheetIndex(0)
 ->setCellValue('A1','Hello')
 ->setCellValue('B1','World');

//redirect to browser (download) instead of saving the result as a file

//this is for MS Office Excel 2007 xlsx format
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="test.xlsx"');

//this is for MS Office Excel 2003 xls format
//header('Content-Type: application/vnd.ms-excel');
//header('Content-Disposition: attachment; filename="test.xlsx"');


header('Cache-Control: max-age=0');

//write the result to a file
//for excel 2007 format
$file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');

//for excel 2003 format
//$file = PHPExcel_IOFactory::createWriter($excel,'Excel5');

//output to php output instead of filename
$file->save('php://output');

?>

You can choose in what format the excel file will be generated by uncomment/comment the headers and IOFactory line.

Basically, what needs to be change to save it in different formats is:
for Excel 2007 or above
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="test.xlsx"');
$file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');

and for Excel 2003
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="test.xls"');
$file = PHPExcel_IOFactory::createWriter($excel,'Excel5');

And here's the video if you need a step-by-step explanation.

Part #1 How to install and test php excel (basic usage).

Part #2 Download PHP Generated Excel File.

71 comments :

Post a Comment

Conditional Formatting in PHPExcel

2 comments
Doing conditional formatting in PHPExcel is pretty easy. First you have to define the formatting. Then apply it to a cell.

I hope this snippet could be useful.
<?php
...
$objConditional = new PHPExcel_Style_Conditional();
$objConditional->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS)
                ->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN)
                ->addCondition('B2')
                ->getStyle()
                ->applyFromArray(
 array(
  'font'=>array(
   'color'=>array('argb'=>'FF000000')
  ),
  'fill'=>array(
   'type' =>PHPExcel_Style_Fill::FILL_SOLID,
   'startcolor' =>array('argb' => 'FFFF0000'),
   'endcolor' =>array('argb' => 'FFFF0000')
  )
 )
);
$conditionalStyles = $objPHPExcel->getActiveSheet()->getStyle('C2')->getConditionalStyles();
array_push($conditionalStyles,$objConditional);
$objPHPExcel->getActiveSheet()->getStyle('C2')->setConditionalStyles($conditionalStyles);

B2 is the reference cell, and C2 is the cell for conditional formating to be applied to.

By the way, not everything went smooth when i did this, because the "fill" style doesn't works while the "font" style works well. I spend hour to scour the documentation, and search every possible keywords in google before i finally found what the problem is.
If you want to use SOLID fill, you need to use 'startcolor' instead of 'color'.
That's it. Simple matter but cost me my worthy minutes.
P.S: If you want to use textual conditional formatting insetad of numeric data. Check out Krazal's comment below.

2 comments :

Post a Comment

How to set up XAMPP-bundled php path in windows 7

2 comments
Most student, teacher, or even web developer used bundled webserver applications for their projects such as xampp or uniserv.

When using native php installation, we may use 'php' command directly from command prompt / terminal to use php cli. But if we are using xampp, because the php executable path is not defined in the system environment by default, we need to call php executable bin by complete path such as 'C:\xampp\php\php.exe' everytime to run php cli which is very annoying.

To avoid doing so, we can manually define php executable path in windows system environment You can do that by following these steps.

First, find out where your php executable is located. In XAMPP, it's in C:\xampp\php by default. You may copy the path from address bar to avoid typo.
Next, open your Environment variables by going through : Left click My Computer, Properties, Advanced system settings, and then click Environment Variables.

Choose PATH from System Variables, Edit...

Then at the end of Variable Value, Add (DO NOT REPLACE ANYTHING, just append at the end) a semicolon, followed by your php executable path so it will looks like:
<anotherEntries>;C:\xampp\php
Every entries are separated by semicolon

Hit OK three times to close all windows.

Open your command prompt, and try command:
php -v

your current php version should be displayed. which means from now on you can directly call 'php' from your command prompt to use php cli.

That concludes this tutorial. You can watch the video below to understand this tutorial better.



2 comments :

Post a Comment

Mikrotik | How to Solve Blocked DNS Port (53) Under Hotspot Network

1 comment
After i implement hotspot network in my workplace, everything went smooth. But after awhile, a problem arise. We, anyone behind hotspot, could not resolve some DNS, especially the one hosted by google such as customized blogger domain like this blog, asudahlah.com.

I can ping asudahlah.com using mikrotik terminal in winbox, but i cannot nslookup it in my laptop and my coworker's laptop. I also try with another domain name, some of them get thru, some didn't. My DNS flow goes like this:

Client (DNS=192.168.68.1)-------->(IP=192.168.68.1) Mikrotik (DNS=8.8.8.8)------->internet.

After some trial and error, i found what the problem is. Mikrotik's hotspot dynamically created a NAT rules which redirect DNS port TCP 53 and UDP 53 in order for the captive portal to work.

Here's a solution which works for my case. By bypassing TCP and UDP port 53. Here's the configuration:

/ip firewall nat
add action=accept chain=pre-hotspot disabled=no dst-port=53 protocol=udp
add action=accept chain=pre-hotspot disabled=no dst-port=53 protocol=tcp
/ip hotspot walled-garden ip
add action=accept disabled=no dst-port=53 protocol=udp
add action=accept disabled=no dst-port=53 protocol=tcp


Well, that's it. Now i can access all domain.

I hope it helps anyone having the same problem.

1 comment :

Post a Comment

How to check battery status in ubuntu using command terminal

No comments
On linux, we can find out information and status of the battery through the terminal. Here's a very short tutorial on how to see the status of the battery through terminal with upower command, and a tips to make it lot easier.

Upower is an abstraction for enumerating devices, power devices, activity monitor and update the query history and statistics. Created by freedesktop.org. Information and complete documentation can be visited at http://upower.freedesktop.org/.

To view battery information, the first is to search path for device battery with the command:

upower -e

Then some device path will show up like example below:


/org/freedesktop/UPower/devices/line_power_ADP0
/org/freedesktop/UPower/devices/battery_BAT0
/org/freedesktop/UPower/devices/DisplayDevice

If it the device path list does not appear like above, but instead the error message "command not found" that means upower is not installed (Which is very rare occasion in linux OS). Please install first upower with command:
sudo apt-get install upower
for ubuntu, debian, mint and it's kind.



Each of 3 paths above pointing to the power devices, such as, in the above example is the line power (AC adapter), battery, and display device.

After we figure out the path for the battery, in the case above, it's /org/freedesktop/UPower/devices/battery_BAT0, then we can check the battery status with the command:

upower -i /org/freedesktop/UPower/devices/battery_BAT0

It will output some information like below:

native-path:          BAT0
vendor:               <a class="zem_slink" title="Laptop" href="http://en.wikipedia.org/wiki/Laptop" target="_blank" rel="wikipedia">NOTEBOOK</a>
model:                BAT
serial:               0001
power supply:         yes
updated:              Sat 29 Aug 2015 10:51:07 PM WIB (107 seconds ago)
has history:          yes
has statistics:       yes
battery
present:             yes
rechargeable:        yes
state:               discharging
warning-level:       none
<a class="zem_slink" title="Energy" href="http://en.wikipedia.org/wiki/Energy" target="_blank" rel="wikipedia">energy</a>:              19.9911 Wh
energy-empty:        0 Wh
energy-full:         31.3797 Wh
energy-full-design:  48.84 Wh
energy-rate:         12.9156 W
voltage:             14.8 V
time to empty:       1.5 hours
percentage:          63%
capacity:            64.25%
technology:          <a class="zem_slink" title="Lithium-ion battery" href="http://en.wikipedia.org/wiki/Lithium-ion_battery" target="_blank" rel="wikipedia">lithium-ion</a>
icon-name:          'battery-full-symbolic'
History (charge):
1440863467    63.000    discharging
History (rate):
1440863467    12.916    discharging


From the information above, we know that my laptop isn't connected to a charger / power source (state = discharging). Battery energy (energy) 19.9911 Wh or 63%.in percentage.

Full battery (energy-full) 31.3797 Wh. Which means my battery life have been degraded, and could only be charged until it reach 31.3797 Wh, which is, by design, supposed to be (energy-full-design) 48.84 Wh. Its max capacities (capacity) has been reduced from the original 64.25% (new).

You may experiment and observe other information.

How to make a shortcut to check laptop batteries in terminal


Now to make it even easier, we can create a command alias/shortcut for the above commands.

It's as simple as editiing the .bashrc file. in your home directory:

nano ~/.bashrc

If the file does not exist (empty), try to replace it with the file. bash_profile or. profile.

And then on top of the lines, add the line:


alias battery='upower -i /org/freedesktop/UPower/devices/battery_BAT0'


change 'battery' onto whatever word you like without any spaces.

Save and execute:


source ~/.bashrc

to reload your .bashrc or .bash_profile flle.

Then try your newly defined alias.

No comments :

Post a Comment

File Transfer over network using SSH and File Manager

4 comments
There are many ways to transfer files over the network on linux ubuntu, by using samba server, http server, ftp, sftp, and many more. One of the most accessible among them and the one I will discuss this time is to use SFTP (SSH File Transfer Protocol). in other words, transfer files through SSH.

There are 3 basic requirements for this method:

  1. The network is set up in such a way so as to allow each computer to ping.

  2. SSH server on the computer that will be accessed must be installed, enabled, and can be accessed/login from another computer. For a guide to installing SSH Server, you can read in the article how to enable and configure SSH Server on ubuntu

  3. Applications such as file manager nautilus, nemo, thunar, etc. (in this example I use the default ubuntu Nautilus) already installed on the client computer to access.


How to connect file manager to SFTP


Method 1 of 2


Open file manager (in this example, nautilus).

Then click file menu or context menu (gear/cog icon on top-right of nautilus window). Then choose "Connect to server..." like in the picture below.



Then in the "connect to server" dialog, enter the destination address along with the sftp Protocol. In the example picture below I used the address 192.168.6.2, so the address is: sftp://192.168.6.2


If after clicking "Connect" nothing happens, maybe the addresses that you entered could not be accessed. Make sure that the ip address is ping-able and SSH server is running on that computer.

When the destination computer's SSH server using tcp port other than the default port of the ssh (port 22), then add the port number after the colon (:) for example sftp://192.168.6.2:1234



Then click the "Connect" button. And wait until the login proccess is success, the nautilus will open the home directory of the user that you use to login.
To enter another directory such as/,/var/www,/etc, press "Ctrl + L", and then in the address / location bar, delete addresses that point to the home directory. Example: sftp://192.168.6.2/home/asudahlah becomes sftp://192.168.6.2/or sftp://192.168.6.2/var/www

 

Method 2 of 2


This way more simple than the first. 😀 you just need to press "Ctrl + L", then enter the IP address of the destination and its protocol such as sftp://192.168.6.2/, and then press enter. And the login dialog will appear and you can read the next steps in the method 1. 😀 that's it.

P.S


Just like FTP, these methods uses client-server. Where the client can access the server, but not vice versa. However, you can delete, create, transmit, and retrieve files depending on the access rights / permission of the user you used when logged in.

In file manager, a connection that you create will just be treated as a directory as if in mount and is usually displayed on the sidebar.

4 comments :

Post a Comment

How to fix MS office crash in wine caused by my network places

1 comment
On some occasions users of MS Office in wine get annoyed because Ms Office crash or not responding when they're about to save their works, resulting in loss of all the works. And mostly it caused by accidentally click "my network places" location in save dialog.



And it's very annoying because the whole work that is already done is lost because it could not be saved. We may be able to recover it. but still, it's annoying.

When in windows, that won't be a problem. But in wine, because basically we are not running the windows operating system so that the path to my network places leads to nowhere, causing infinite loading when you access it.

The only way (IMHO) to fix the problem is to not display that problematic button at all in order to avoid "accidental click".

How to hide my network places icon in MS Office save dialog



  1. The first step is to open the registry editor, do I run the winetrick application.

  2. Then select the menu "select the default wineprefix".

  3. Choose "run regedit".

  4. After the registry editor, go to:
    HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Common\Open Find\Places\StandardPlacesNote: The colored green may be different, depending on the version of office that you have. just select the number of the most high.

  5. Then on each key that exists in the StandardPlaces, change the DWORD registry value of "Show" to 0 by right click on the registry in the right pane, and then select modify, change the Value to 0, and then OK. (If there are any registry named "View", change also the value to 0).

    If no registry DWORD named "Show", please create your own way right dipanel right click and select New DWORD Value >, then give the name of the "Show" without the quotation marks and then enter. By default its Value is 0.

  6. Repeat step 5 and 6 for key Recent, Publishing, My Computer and Desktop

  7. Make sure it is correct, and then exit the registry.

  8. Please try opening the application MS Office again, and then open the file. It should be in the left panel there is no my network places.


This concludes the short tutorials of how to fix MS office crash in wine caused by my network places.

Hope it could help anyone facing the same problem.

1 comment :

Post a Comment

How to fix "error Could not get lock /var/lib/dpkg/lock resource temporarily unavailable" in ubuntu

No comments
Often when we do the apt commands, whether it be to install, update, or uninstall/remove. We'll likely encountered a problem, ranging from a mere trivial to an annoying error which makes it impossible to continue the process. One of the most common error message is:

[code lang="bash"] E: Could not get lock/var/lib/dpkg/lock-open (11 Resource be temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it? [/code]

Generally this is because we forcibly stop or interrupt the process when performing the apt-get command. Usually with Ctrl + C or interrupt (halt). It causes the process to suddenly stop and the apt didn't manage to open the lock that prevents the apt process from running simultaneously.

Basically, the apt is not allowed to run more than one process, because it can mess up the dependencies. So it requires a lock to make sure that there is only 1 process running. When we run the command apt, apt will then automatically create a lock, and when we try to run another apt command, the apt will check if there is a lock, if any, then the second apt process will stop and display the error message above.

Sometimes, when the apt process is forced to stop or interrupted (halt), the process had not previously delete the apt lock. So the apt command we try to run will recognize that there is an apt processes running, despite there isn't. And in the end, the apt will terminate with error.

The fix is pretty easy, we just need to remove the lock manually. But to do so, we need root privileges.
Just with the command:

[code lang="bash"] sudo rm/var/lib/apt/lists/lock [/code] or

[code lang="bash"] sudo rm/var/cache/apt/archives/lock [/code]

Then try to run apt-get command again.
well, that's it. easy isn't it?

I hope this helps anyone.

No comments :

Post a Comment

How to add PPA repository in ubuntu linux

No comments
The PPA is a linux repository on a non-official, used to accommodate the developer's applications which are not included into the indi repository official/official. Often when we want to install an application program on linux, it turns out there hasn't been in the official repository. The existence of this PPA repository, we do not need to download the source application, and then mengcompile himself of course troublesome and not necessarily the application runs perfect.

We just need to add an entry into our repository ppa, and applications that exist on the ppa repository can we install with package manager.

There are several ways to add the ppa repository, I am just going to cover 2 ways, namely through the terminal and gui.
Add the PPA repository through the terminal

Open a terminal emulator, and then enter the command:

[code lang="bash"] sudo add-apt-repository ppa: achadwick/mypaint-testing [/code]

Which the ppa: achadwick/mypaint-testing is the ppa entry that you can get on the website launcpad.net for the application in question.
Add the PPA repository through GUI (Software Source)

Open Software Sources, and then enter your password.

then:

Click the tab of the PPA
Click Add new PPA
Copas entry PPA
Click OK, and then follow the process.
If the process is completed, click refresh list

 
add ubuntu ppa

No comments :

Post a Comment

How to fix missing suspend function in cinnamon ubuntu

No comments
After a long time using xfce in my ubuntu laptop. Finally a few days ago I had to replace my desktop into cinnamon.

Till now, I never turn off/shut down my laptop. Whenever I finished using my laptop, i always suspend it, because i don't want to wait for a long boot time when i want to use it again.

Well, there's a problem showed up after I install cinnamon desktop. There are no suspend menu when click quit in the launcher. Which only shows "Restart", "Cancel" and "Shut Down".

In my case, the source of the problem is the cinnamon default session setting does not use logind. You can use the command to see what the settings are:

gsettings get org.cinnamon.desktop.session settings-daemon-uses-logind

gsettings get org. cinnamon. desktop. session session-manager-uses-logind


If both of the above commands output "false". Then it means cinnamon session does not use logind. We should set it up manually with these commands:
gsettings set org.cinnamon.desktop.session settings-daemon-uses-logind true
gsettings set org.cinnamon.desktop.session session-manager-uses-logind true
gsettings set org.cinnamon.desktop.session screensaver-uses-logind false


After restart, suspend button now appears in window session

Finally I can suspend my laptop.

But.... here comes another problem, When the laptop lid is closed, my ubuntu doesn't suspend. Although in the power settings I have set it up that way.

And again, Finally I found a solution, it's very simple, just uncomment a single line in a configuration file:

/etc/systemd/logind.conf

use your favorite text editor to change this, do not forget the sudo command.

sudo nano /etc/systemd/logind.conf

Locate the line that contains the configuration of "HandleLidSwitch = suspend", then uncheck the fence at the beginning of the line. (uncomment).

Then restart, my "suspend" problems on my ubuntu laptop cinnamon is now gone.

After that, there are many more problems that I encountered during the transition to the cinnamon. which I'll share in another post.

I hope this badly organized post can be useful.

No comments :

Post a Comment

Tutorial membuat Kalkulator IP Address dengan javascript & html (video)

3 comments
Step 1

[code lang="html"]<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>[/code]

 

Step 2

[code lang="html"] <title>IP Calculator</title>[/code]

Step 3

[code lang="html"] <h1>IP Address calculator</h1>[/code]

Step 4

[code lang="html"] IP Address
<input type='text' class='addr' id='q1'> .
<input type='text' class='addr' id='q2'> .
<input type='text' class='addr' id='q3'> .
<input type='text' class='addr' id='q4'> /
<input type='text' class='addr' id='cidr'>
<button>Calculate</button>[/code]

 

Step 5

[code lang="html"] <style>
body {
font-family:monospace;
font-size:16px;
}
.addr {
width:30px;
}
</style>[/code]

 

Step 6

[code lang="html"] <hr>
<div class='result'>
<span class=label>IP Address :</span>
<span class=value id=resIP></span>
</div>
<div class='result'>
<span class=label>Subnet mask :</span>
<span class=value id=resMask></span>
</div>
<div class='result'>
<span class=label>Net Address :</span>
<span class=value id=resNet></span>
</div>
<div class='result'>
<span class=label>Broadcast Address :</span>
<span class=value id=resBC></span>
</div>
<div class='result'>
<span class=label>Standard Class :</span>
<span class=value id=resClass></span>
</div>
<div class='result'>
<span class=label>Range :</span>
<span class=value id=resRange></span>
</div>
<div class='result'>
<span class=label>IP Binary :</span>
<span class=value id=resBinIP></span>
</div>
<div class='result'>
<span class=label>Mask Binary :</span>
<span class=value id=resBinMask></span>
</div>
<div class='result'>
<span class=label>Net Address Binary :</span>
<span class=value id=resBinNet></span>
</div>
<div class='result'>
<span class=label>BC Address Binary :</span>
<span class=value id=resBinBC></span>
</div>[/code]

 

Step 7

[code lang="css"].result {
border-bottom: 1px solid #6a6ade;
border-right: 1px solid #6a6ade;
}
.result .label {
display:inline-block;
width:200px;
background:#aaf;
}[/code]

Step 8

[code lang="html"] <script type='text/javascript'>
function calculate(){
alert("calculate button pressed");
}
</script>[/code]

Step 9

[code lang="html"] <button onclick='calculate();'>Calculate</button>[/code]

Step 10

[code lang="javascript"]//get values from input box
var q1=document.getElementById('q1').value;
var q2=document.getElementById('q2').value;
var q3=document.getElementById('q3').value;
var q4=document.getElementById('q4').value;
var cidr=document.getElementById('cidr').value;

//validate input value
if(
(q1>=0 && q1<=255) &&
(q2>=0 && q2<=255) &&
(q3>=0 && q3<=255) &&
(q4>=0 && q4<=255) &&
(cidr>=0 && cidr<=32)
){
//display IP address
document.getElementById('resIP').innerHTML=q1 + "." + q2 + "." + q3 + "." + q4;

//get IP Address binaries
var ipBin={};
ipBin[1]=String("00000000"+parseInt(q1,10).toString(2)).slice(-8);
ipBin[2]=String("00000000"+parseInt(q2,10).toString(2)).slice(-8);
ipBin[3]=String("00000000"+parseInt(q3,10).toString(2)).slice(-8);
ipBin[4]=String("00000000"+parseInt(q4,10).toString(2)).slice(-8);

//decide standart class
var standartClass="";
if(q1<=126) {
standartClass="A";
}else if (q1==127) {
standartClass="loopback IP"
}else if (q1>=128 && q1<=191) {
standartClass="B";
}else if (q1>=192 && q1<=223) {
standartClass="C";
}else if (q1>=224 && q1<=239) {
standartClass="D (Multicast Address)";
}else if (q1>=240 && q1<=225) {
standartClass="E (Experimental)";
}else {
standartClass="Out of range";
}

//netmask
var mask=cidr;
var importantBlock=Math.ceil(mask/8);
var importantBlockBinary=ipBin[importantBlock];
var maskBinaryBlockCount=mask%8;
if(maskBinaryBlockCount==0)importantBlock++;
var maskBinaryBlock="";
var maskBlock="";
for(var i=1;i<=8;i++){
if(maskBinaryBlockCount>=i){
maskBinaryBlock+="1";
}else{
maskBinaryBlock+="0";
}
}
//convert binary mask block to decimal
maskBlock=parseInt(maskBinaryBlock,2);

//net & broadcast addr
var netBlockBinary="";
var bcBlockBinary="";
for(var i=1;i<=8;i++){
if(maskBinaryBlock.substr(i-1,1)=="1"){
netBlockBinary+=importantBlockBinary.substr(i-1,1);
bcBlockBinary+=importantBlockBinary.substr(i-1,1);
}else{
netBlockBinary+="0";
bcBlockBinary+="1";
}
}

//put everything together, create a string container variables
var mask="";
var maskBinary="";
var net="";
var bc="";
var netBinary="";
var bcBinary="";
var rangeA="";
var rangeB="";
//loop to put whole strings block together
for(var i=1;i<=4;i++){
if(importantBlock>i) {
//blocks before the important block.
mask+="255";
maskBinary+="11111111";
netBinary+=ipBin[i];
bcBinary+=ipBin[i];
net+=parseInt(ipBin[i],2);
bc+=parseInt(ipBin[i],2);
rangeA+=parseInt(ipBin[i],2);
rangeB+=parseInt(ipBin[i],2);
}else if (importantBlock==i) {
//the important block.
mask+=maskBlock;
maskBinary+=maskBinaryBlock;
netBinary+=netBlockBinary;
bcBinary+=bcBlockBinary;
net+=parseInt(netBlockBinary,2);
bc+=parseInt(bcBlockBinary,2);
rangeA+=(parseInt(netBlockBinary,2)+1);
rangeB+=(parseInt(bcBlockBinary,2)-1);
}else {
//block after the important block.
mask+=0;
maskBinary+="00000000";
netBinary+="00000000";
bcBinary+="11111111";
net+="0";
bc+="255";
rangeA+=0;
rangeB+=255;
}
//add . separator except the last block
if(i<4){
mask+=".";
maskBinary+=".";
netBinary+=".";
bcBinary+=".";
net+=".";
bc+=".";
rangeA+=".";
rangeB+=".";
}
}
//write the results to the page.
document.getElementById('resMask').innerHTML=mask;
document.getElementById('resNet').innerHTML=net;
document.getElementById('resBC').innerHTML=bc;
document.getElementById('resRange').innerHTML=rangeA + " - " + rangeB;
document.getElementById('resBinIP').innerHTML=ipBin[1]+"."+ipBin[2]+"."+ipBin[3]+"."+ipBin[4];
document.getElementById('resBinMask').innerHTML=maskBinary;
document.getElementById('resBinNet').innerHTML=netBinary;
document.getElementById('resBinBC').innerHTML=bcBinary;
document.getElementById('resClass').innerHTML=standartClass;
}else{
alert("invalid value");
}
[/code]

Instruction video



Another version.


As requested by one of my subscriber. I made some customization which allows the calculator to guess subnet id using provided possible hosts number.

[code lang="html"]<!DOCTYPE html>
<html>
<head>
<title>IP Calculator</title>
<style>
body {
font-family:monospace;
font-size:16px;
}
.addr {
width:30px;
}
.result {
border-bottom: 1px solid #6a6ade;
border-right: 1px solid #6a6ade;
}
.result .label {
display:inline-block;
width:200px;
background:#aaf;
}
</style>
</head>
<body>
<h1>IP Address calculator</h1>
IP Address
<input type='text' class='addr' id='q1'> .
<input type='text' class='addr' id='q2'> .
<input type='text' class='addr' id='q3'> .
<input type='text' class='addr' id='q4'>
<br>
# of host
<input type='text' class='addr' id='hostNum'><br>
# of subnet
<input type='text' class='addr' id='subnetNum'>
<br>
Note:
<br>
Netmask will be automatically guessed using #of host first
<br>
# of subnet isn't really used here as the netmask is already guessed from # of host
<br>
<button onclick='calculate();'>Calculate</button>
<hr>
<div class='result'>
<span class=label>IP Address :</span>
<span class=value id=resIP></span>
</div>
<div class='result'>
<span class=label>Subnet mask :</span>
<span class=value id=resMask></span>
</div>
<div class='result'>
<span class=label>Subnet Id (CIDR) :</span>
<span class=value id=resSubnetId></span>
</div>
<div class='result'>
<span class=label>Net Address :</span>
<span class=value id=resNet></span>
</div>
<div class='result'>
<span class=label>Broadcast Address :</span>
<span class=value id=resBC></span>
</div>
<div class='result'>
<span class=label>Standard Class :</span>
<span class=value id=resClass></span>
</div>
<div class='result'>
<span class=label>Important Block :</span>
<span class=value id=resImportantBlock></span>
</div>
<div class='result'>
<span class=label>Range :</span>
<span class=value id=resRange></span>
</div>
<div class='result'>
<span class=label>IP Binary :</span>
<span class=value id=resBinIP></span>
</div>
<div class='result'>
<span class=label>Mask Binary :</span>
<span class=value id=resBinMask></span>
</div>
<div class='result'>
<span class=label>Net Address Binary :</span>
<span class=value id=resBinNet></span>
</div>
<div class='result'>
<span class=label>BC Address Binary :</span>
<span class=value id=resBinBC></span>
</div>
<div class='result'>
<span class=label>Max # of Subnet :</span>
<span class=value id=resMaxNet></span>
</div>
<div class='result'>
<span class=label>Max # of Host :</span>
<span class=value id=resMaxHost></span>
</div>
<div style=font-size:11px;><a href="http://asudahlah.com">By. Gemul Cybermujahidz</a></div>
</body>
<script type='text/javascript'>
function calculate(){
//get values from input box
var q1=document.getElementById('q1').value;
var q2=document.getElementById('q2').value;
var q3=document.getElementById('q3').value;
var q4=document.getElementById('q4').value;
//var cidr=document.getElementById('cidr').value;
var netNum=document.getElementById('subnetNum').value;
var hostNum=document.getElementById('hostNum').value;

//guessing netmask by # of host
var hostNumDbg=0;
for(var i=32;i>=0;i--){
if(hostNum >= Math.pow(2,i)){
//hostNumDbg=Math.pow(2,i+1);
hostNumDbg=32-(i+1);
break;
}
}
var cidr=hostNumDbg;


//validate input value
if(
(q1>=0 && q1<=255) &&
(q2>=0 && q2<=255) &&
(q3>=0 && q3<=255) &&
(q4>=0 && q4<=255) &&
(cidr>=0 && cidr<=32)
){
//display IP address
document.getElementById('resIP').innerHTML=q1 + "." + q2 + "." + q3 + "." + q4;

//get IP Address binaries
var ipBin={};
ipBin[1]=String("00000000"+parseInt(q1,10).toString(2)).slice(-8);
ipBin[2]=String("00000000"+parseInt(q2,10).toString(2)).slice(-8);
ipBin[3]=String("00000000"+parseInt(q3,10).toString(2)).slice(-8);
ipBin[4]=String("00000000"+parseInt(q4,10).toString(2)).slice(-8);

//decide standart class

var standartClass="";
if(q1<=126) {
standartClass="A";
}else if (q1==127) {
standartClass="loopback IP"
}else if (q1>=128 && q1<=191) {
standartClass="B";
}else if (q1>=192 && q1<=223) {
standartClass="C";
}else if (q1>=224 && q1<=239) {
standartClass="D (Multicast Address)";
}else if (q1>=240 && q1<=225) {
standartClass="E (Experimental)";
}else {
standartClass="Out of range";
}

//netmask
var mask=cidr;
var importantBlock=Math.ceil(mask/8);
var importantBlockBinary=ipBin[importantBlock];
var maskBinaryBlockCount=mask%8;
if(maskBinaryBlockCount==0)importantBlock++;
var maskBinaryBlock="";
var maskBlock="";
for(var i=1;i<=8;i++){
if(maskBinaryBlockCount>=i){
maskBinaryBlock+="1";
}else{
maskBinaryBlock+="0";
}
}
//convert binary mask block to decimal
maskBlock=parseInt(maskBinaryBlock,2);

//net & broadcast addr
var netBlockBinary="";
var bcBlockBinary="";
for(var i=1;i<=8;i++){
if(maskBinaryBlock.substr(i-1,1)=="1"){
netBlockBinary+=importantBlockBinary.substr(i-1,1);
bcBlockBinary+=importantBlockBinary.substr(i-1,1);
}else{
netBlockBinary+="0";
bcBlockBinary+="1";
}
}

//put everything together, create a string container variables
var mask="";
var maskBinary="";
var net="";
var bc="";
var netBinary="";
var bcBinary="";
var rangeA="";
var rangeB="";
//loop to put whole strings block together
for(var i=1;i<=4;i++){
if(importantBlock>i) {
//blocks before the important block.
mask+="255";
maskBinary+="11111111";
netBinary+=ipBin[i];
bcBinary+=ipBin[i];
net+=parseInt(ipBin[i],2);
bc+=parseInt(ipBin[i],2);
rangeA+=parseInt(ipBin[i],2);
rangeB+=parseInt(ipBin[i],2);
}else if (importantBlock==i) {
//the important block.
mask+=maskBlock;
maskBinary+=maskBinaryBlock;
netBinary+=netBlockBinary;
bcBinary+=bcBlockBinary;
net+=parseInt(netBlockBinary,2);
bc+=parseInt(bcBlockBinary,2);
rangeA+=(parseInt(netBlockBinary,2)+1);
rangeB+=(parseInt(bcBlockBinary,2)-1);
}else {
//block after the important block.
mask+=0;
maskBinary+="00000000";
netBinary+="00000000";
bcBinary+="11111111";
net+="0";
bc+="255";
rangeA+=0;
rangeB+=255;
}
//add . separator except the last block
if(i<4){
mask+=".";
maskBinary+=".";
netBinary+=".";
bcBinary+=".";
net+=".";
bc+=".";
rangeA+=".";
rangeB+=".";
}
}

//additional : count maximum host, maximum net and current subnets
var binaryHost="";
for(var i=(31-cidr);i>=0;i--){
binaryHost=binaryHost+"1";
}
var maxHost=parseInt(binaryHost,2);
var binarySubnet="";
for(var i=cidr;i>=0;i--){
binarySubnet=binarySubnet+"1";
}
var maxSubnet=parseInt(binarySubnet,2);
var binaryCurrentSubnetBlock="";
for(var i=maskBinaryBlockCount;i>=0;i--){
binaryCurrentSubnetBlock=binaryCurrentSubnetBlock+"1";
}
var maxCurrentSubnetBlock=parseInt(binaryCurrentSubnetBlock,2);

//write the results to the page.
document.getElementById('resMask').innerHTML=mask;
document.getElementById('resNet').innerHTML=net;
document.getElementById('resBC').innerHTML=bc;
document.getElementById('resRange').innerHTML=rangeA + " - " + rangeB;
document.getElementById('resBinIP').innerHTML=ipBin[1]+"."+ipBin[2]+"."+ipBin[3]+"."+ipBin[4];
document.getElementById('resBinMask').innerHTML=maskBinary;
document.getElementById('resBinNet').innerHTML=netBinary;
document.getElementById('resBinBC').innerHTML=bcBinary;
document.getElementById('resClass').innerHTML=standartClass;
document.getElementById('resSubnetId').innerHTML=cidr;
document.getElementById('resMaxHost').innerHTML=maxHost+" possible host(s) in current subnet";
document.getElementById('resMaxNet').innerHTML=maxSubnet+" of total possible subnet, "+maxCurrentSubnetBlock+" possible subnet in current block";
document.getElementById('resImportantBlock').innerHTML=importantBlock;
}else{
alert("invalid value");
}

}
</script>
</html>
[/code]

3 comments :

Post a Comment

TP-Link Access Point/router batch reboot/restarter php script

54 comments
Untuk versi bahasa indonesia, silahkan klik disini

If you have a large wireless network infrastructure, which consist of many Access point and Wi-Fi router. And at some cases, you need to safely reboot all access point. It could be very annoying if you have to login to each AP/Router and restart them individually one by one.

Why bother doing all those work manually when you could write a code to do it automatically?

Well, luckily in my cases, all of the access point have the same brand. it's TP-Link. After some research, i found a way to reboot those brand's access point and router by using URL. Then i wrote this PHP script to get the job done.

In my infrastructure, i made all access point and router have different IP sub from DHCP-ed network. All have same username and password, all have the same method of authentication (using http auth). This script written in PHP, running in terminal/console. So it's very handy when it comes to automation. Just add it to cron and voila. Don't forget to make it executable "chmod 777" if you want to run it under linux and make sure you have php5-cli installed.

Here i share the script i wrote, you can customize it to suit your infrastructure, be creative.


#!/usr/bin/php

<?php

//----------Auth config

$apUser="admin";

$apPass="admin";

//----------Lists of AP and it's IP address

$apList=Array(

Array("Ext1","192.168.0.15"),

Array("Ext2","192.168.0.17"),

Array("Jalak","192.168.0.2"),

Array("Barat","192.168.0.3"),

Array("-","192.168.0.5"),

Array("Parkit","192.168.0.6"),

Array("Murai","192.168.0.9"),

Array("Nuri","192.168.0.10"),

Array("Kenari","192.168.0.12"),

Array("Cucak","192.168.0.13"),

Array("Hud-Hud","192.168.0.14"),

);



function curl_download($ip){

$Url="http://".$ip."/userRpm/SysRebootRpm.htm?Reboot=Reboot";

// is cURL installed yet?

if (!function_exists('curl_init')){

die('Sorry cURL is not installed!');

}



// OK cool - then let's create a new cURL resource handle

$ch = curl_init();



// Set URL to download

curl_setopt($ch, CURLOPT_REFERER, "http://".$ip."/userRpm/SysRebootRpm.htm");

curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux i686;rv:12.0) Gecko/20100101 Firefox/12.0");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_URL, $Url);

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

curl_setopt($ch, CURLOPT_USERPWD, $apUser.":".$apPass);

curl_setopt($ch, CURLOPT_TIMEOUT, 120);



$output = curl_exec($ch);



curl_close($ch);



return $output;

}



print "\n";

print "\e[1;34mAP Resetter. By Cybermujahidz\e[0m\n";

print "\n";

print "List of AP:\n";

foreach($apList as $ap){

print str_pad($ap[1],15,' ',STR_PAD_RIGHT)." ".str_pad($ap[0],10,' ',STR_PAD_RIGHT)." queued\n";

}

print "\n";

print "Resetting ALL AP\n";

print "----------------\n";

foreach($apList as $ap){

if(curl_download($ap[1])){

print str_pad($ap[1],15,' ',STR_PAD_RIGHT)." ".str_pad($ap[0],10,' ',STR_PAD_RIGHT)." [ \e[1;32mAP Rebooted\e[0m ]\n";

}else{

print str_pad($ap[1],15,' ',STR_PAD_RIGHT)." ".str_pad($ap[0],10,' ',STR_PAD_RIGHT)." [ \e[1;31m AP Down \e[0m ]\n";

}

}

print "AP reset finished.\n";

print "------------------\n";

?>

54 comments :

Post a Comment

How to make IP Address Calculator using HTML & Javascript

8 comments
Step 1

[code lang="html"]<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>[/code]

 

Step 2

[code lang="html"] <title>IP Calculator</title>[/code]

Step 3

[code lang="html"] <h1>IP Address calculator</h1>[/code]

Step 4

[code lang="html"] IP Address
<input type='text' class='addr' id='q1'> .
<input type='text' class='addr' id='q2'> .
<input type='text' class='addr' id='q3'> .
<input type='text' class='addr' id='q4'> /
<input type='text' class='addr' id='cidr'>
<button>Calculate</button>[/code]

 

Step 5

[code lang="html"] <style>
body {
font-family:monospace;
font-size:16px;
}
.addr {
width:30px;
}
</style>[/code]

 

Step 6

[code lang="html"] <hr>
<div class='result'>
<span class=label>IP Address :</span>
<span class=value id=resIP></span>
</div>
<div class='result'>
<span class=label>Subnet mask :</span>
<span class=value id=resMask></span>
</div>
<div class='result'>
<span class=label>Net Address :</span>
<span class=value id=resNet></span>
</div>
<div class='result'>
<span class=label>Broadcast Address :</span>
<span class=value id=resBC></span>
</div>
<div class='result'>
<span class=label>Standard Class :</span>
<span class=value id=resClass></span>
</div>
<div class='result'>
<span class=label>Range :</span>
<span class=value id=resRange></span>
</div>
<div class='result'>
<span class=label>IP Binary :</span>
<span class=value id=resBinIP></span>
</div>
<div class='result'>
<span class=label>Mask Binary :</span>
<span class=value id=resBinMask></span>
</div>
<div class='result'>
<span class=label>Net Address Binary :</span>
<span class=value id=resBinNet></span>
</div>
<div class='result'>
<span class=label>BC Address Binary :</span>
<span class=value id=resBinBC></span>
</div>[/code]

 

Step 7

[code lang="css"].result {
border-bottom: 1px solid #6a6ade;
border-right: 1px solid #6a6ade;
}
.result .label {
display:inline-block;
width:200px;
background:#aaf;
}[/code]

Step 8

[code lang="html"] <script type='text/javascript'>
function calculate(){
alert("calculate button pressed");
}
</script>[/code]

Step 9

[code lang="html"] <button onclick='calculate();'>Calculate</button>[/code]

Step 10

[code lang="javascript"]//get values from input box
var q1=document.getElementById('q1').value;
var q2=document.getElementById('q2').value;
var q3=document.getElementById('q3').value;
var q4=document.getElementById('q4').value;
var cidr=document.getElementById('cidr').value;

//validate input value
if(
(q1>=0 && q1<=255) &&
(q2>=0 && q2<=255) &&
(q3>=0 && q3<=255) &&
(q4>=0 && q4<=255) &&
(cidr>=0 && cidr<=32)
){
//display IP address
document.getElementById('resIP').innerHTML=q1 + "." + q2 + "." + q3 + "." + q4;

//get IP Address binaries
var ipBin={};
ipBin[1]=String("00000000"+parseInt(q1,10).toString(2)).slice(-8);
ipBin[2]=String("00000000"+parseInt(q2,10).toString(2)).slice(-8);
ipBin[3]=String("00000000"+parseInt(q3,10).toString(2)).slice(-8);
ipBin[4]=String("00000000"+parseInt(q4,10).toString(2)).slice(-8);

//decide standart class
var standartClass="";
if(q1<=126) {
standartClass="A";
}else if (q1==127) {
standartClass="loopback IP"
}else if (q1>=128 && q1<=191) {
standartClass="B";
}else if (q1>=192 && q1<=223) {
standartClass="C";
}else if (q1>=224 && q1<=239) {
standartClass="D (Multicast Address)";
}else if (q1>=240 && q1<=225) {
standartClass="E (Experimental)";
}else {
standartClass="Out of range";
}

//netmask
var mask=cidr;
var importantBlock=Math.ceil(mask/8);
var importantBlockBinary=ipBin[importantBlock];
var maskBinaryBlockCount=mask%8;
if(maskBinaryBlockCount==0)importantBlock++;
var maskBinaryBlock="";
var maskBlock="";
for(var i=1;i<=8;i++){
if(maskBinaryBlockCount>=i){
maskBinaryBlock+="1";
}else{
maskBinaryBlock+="0";
}
}
//convert binary mask block to decimal
maskBlock=parseInt(maskBinaryBlock,2);

//net & broadcast addr
var netBlockBinary="";
var bcBlockBinary="";
for(var i=1;i<=8;i++){
if(maskBinaryBlock.substr(i-1,1)=="1"){
netBlockBinary+=importantBlockBinary.substr(i-1,1);
bcBlockBinary+=importantBlockBinary.substr(i-1,1);
}else{
netBlockBinary+="0";
bcBlockBinary+="1";
}
}

//put everything together, create a string container variables
var mask="";
var maskBinary="";
var net="";
var bc="";
var netBinary="";
var bcBinary="";
var rangeA="";
var rangeB="";
//loop to put whole strings block together
for(var i=1;i<=4;i++){
if(importantBlock>i) {
//blocks before the important block.
mask+="255";
maskBinary+="11111111";
netBinary+=ipBin[i];
bcBinary+=ipBin[i];
net+=parseInt(ipBin[i],2);
bc+=parseInt(ipBin[i],2);
rangeA+=parseInt(ipBin[i],2);
rangeB+=parseInt(ipBin[i],2);
}else if (importantBlock==i) {
//the important block.
mask+=maskBlock;
maskBinary+=maskBinaryBlock;
netBinary+=netBlockBinary;
bcBinary+=bcBlockBinary;
net+=parseInt(netBlockBinary,2);
bc+=parseInt(bcBlockBinary,2);
rangeA+=(parseInt(netBlockBinary,2)+1);
rangeB+=(parseInt(bcBlockBinary,2)-1);
}else {
//block after the important block.
mask+=0;
maskBinary+="00000000";
netBinary+="00000000";
bcBinary+="11111111";
net+="0";
bc+="255";
rangeA+=0;
rangeB+=255;
}
//add . separator except the last block
if(i<4){
mask+=".";
maskBinary+=".";
netBinary+=".";
bcBinary+=".";
net+=".";
bc+=".";
rangeA+=".";
rangeB+=".";
}
}
//write the results to the page.
document.getElementById('resMask').innerHTML=mask;
document.getElementById('resNet').innerHTML=net;
document.getElementById('resBC').innerHTML=bc;
document.getElementById('resRange').innerHTML=rangeA + " - " + rangeB;
document.getElementById('resBinIP').innerHTML=ipBin[1]+"."+ipBin[2]+"."+ipBin[3]+"."+ipBin[4];
document.getElementById('resBinMask').innerHTML=maskBinary;
document.getElementById('resBinNet').innerHTML=netBinary;
document.getElementById('resBinBC').innerHTML=bcBinary;
document.getElementById('resClass').innerHTML=standartClass;
}else{
alert("invalid value");
}
[/code]

Instruction video



Another version.


As requested by one of my subscriber. I made some customization which allows the calculator to guess subnet id using provided possible hosts number.

[code lang="html"]<!DOCTYPE html>
<html>
<head>
<title>IP Calculator</title>
<style>
body {
font-family:monospace;
font-size:16px;
}
.addr {
width:30px;
}
.result {
border-bottom: 1px solid #6a6ade;
border-right: 1px solid #6a6ade;
}
.result .label {
display:inline-block;
width:200px;
background:#aaf;
}
</style>
</head>
<body>
<h1>IP Address calculator</h1>
IP Address
<input type='text' class='addr' id='q1'> .
<input type='text' class='addr' id='q2'> .
<input type='text' class='addr' id='q3'> .
<input type='text' class='addr' id='q4'>
<br>
# of host
<input type='text' class='addr' id='hostNum'><br>
# of subnet
<input type='text' class='addr' id='subnetNum'>
<br>
Note:
<br>
Netmask will be automatically guessed using #of host first
<br>
# of subnet isn't really used here as the netmask is already guessed from # of host
<br>
<button onclick='calculate();'>Calculate</button>
<hr>
<div class='result'>
<span class=label>IP Address :</span>
<span class=value id=resIP></span>
</div>
<div class='result'>
<span class=label>Subnet mask :</span>
<span class=value id=resMask></span>
</div>
<div class='result'>
<span class=label>Subnet Id (CIDR) :</span>
<span class=value id=resSubnetId></span>
</div>
<div class='result'>
<span class=label>Net Address :</span>
<span class=value id=resNet></span>
</div>
<div class='result'>
<span class=label>Broadcast Address :</span>
<span class=value id=resBC></span>
</div>
<div class='result'>
<span class=label>Standard Class :</span>
<span class=value id=resClass></span>
</div>
<div class='result'>
<span class=label>Important Block :</span>
<span class=value id=resImportantBlock></span>
</div>
<div class='result'>
<span class=label>Range :</span>
<span class=value id=resRange></span>
</div>
<div class='result'>
<span class=label>IP Binary :</span>
<span class=value id=resBinIP></span>
</div>
<div class='result'>
<span class=label>Mask Binary :</span>
<span class=value id=resBinMask></span>
</div>
<div class='result'>
<span class=label>Net Address Binary :</span>
<span class=value id=resBinNet></span>
</div>
<div class='result'>
<span class=label>BC Address Binary :</span>
<span class=value id=resBinBC></span>
</div>
<div class='result'>
<span class=label>Max # of Subnet :</span>
<span class=value id=resMaxNet></span>
</div>
<div class='result'>
<span class=label>Max # of Host :</span>
<span class=value id=resMaxHost></span>
</div>
<div style=font-size:11px;><a href="http://asudahlah.com">By. Gemul Cybermujahidz</a></div>
</body>
<script type='text/javascript'>
function calculate(){
//get values from input box
var q1=document.getElementById('q1').value;
var q2=document.getElementById('q2').value;
var q3=document.getElementById('q3').value;
var q4=document.getElementById('q4').value;
//var cidr=document.getElementById('cidr').value;
var netNum=document.getElementById('subnetNum').value;
var hostNum=document.getElementById('hostNum').value;

//guessing netmask by # of host
var hostNumDbg=0;
for(var i=32;i>=0;i--){
if(hostNum >= Math.pow(2,i)){
//hostNumDbg=Math.pow(2,i+1);
hostNumDbg=32-(i+1);
break;
}
}
var cidr=hostNumDbg;


//validate input value
if(
(q1>=0 && q1<=255) &&
(q2>=0 && q2<=255) &&
(q3>=0 && q3<=255) &&
(q4>=0 && q4<=255) &&
(cidr>=0 && cidr<=32)
){
//display IP address
document.getElementById('resIP').innerHTML=q1 + "." + q2 + "." + q3 + "." + q4;

//get IP Address binaries
var ipBin={};
ipBin[1]=String("00000000"+parseInt(q1,10).toString(2)).slice(-8);
ipBin[2]=String("00000000"+parseInt(q2,10).toString(2)).slice(-8);
ipBin[3]=String("00000000"+parseInt(q3,10).toString(2)).slice(-8);
ipBin[4]=String("00000000"+parseInt(q4,10).toString(2)).slice(-8);

//decide standart class

var standartClass="";
if(q1<=126) {
standartClass="A";
}else if (q1==127) {
standartClass="loopback IP"
}else if (q1>=128 && q1<=191) {
standartClass="B";
}else if (q1>=192 && q1<=223) {
standartClass="C";
}else if (q1>=224 && q1<=239) {
standartClass="D (Multicast Address)";
}else if (q1>=240 && q1<=225) {
standartClass="E (Experimental)";
}else {
standartClass="Out of range";
}

//netmask
var mask=cidr;
var importantBlock=Math.ceil(mask/8);
var importantBlockBinary=ipBin[importantBlock];
var maskBinaryBlockCount=mask%8;
if(maskBinaryBlockCount==0)importantBlock++;
var maskBinaryBlock="";
var maskBlock="";
for(var i=1;i<=8;i++){
if(maskBinaryBlockCount>=i){
maskBinaryBlock+="1";
}else{
maskBinaryBlock+="0";
}
}
//convert binary mask block to decimal
maskBlock=parseInt(maskBinaryBlock,2);

//net & broadcast addr
var netBlockBinary="";
var bcBlockBinary="";
for(var i=1;i<=8;i++){
if(maskBinaryBlock.substr(i-1,1)=="1"){
netBlockBinary+=importantBlockBinary.substr(i-1,1);
bcBlockBinary+=importantBlockBinary.substr(i-1,1);
}else{
netBlockBinary+="0";
bcBlockBinary+="1";
}
}

//put everything together, create a string container variables
var mask="";
var maskBinary="";
var net="";
var bc="";
var netBinary="";
var bcBinary="";
var rangeA="";
var rangeB="";
//loop to put whole strings block together
for(var i=1;i<=4;i++){
if(importantBlock>i) {
//blocks before the important block.
mask+="255";
maskBinary+="11111111";
netBinary+=ipBin[i];
bcBinary+=ipBin[i];
net+=parseInt(ipBin[i],2);
bc+=parseInt(ipBin[i],2);
rangeA+=parseInt(ipBin[i],2);
rangeB+=parseInt(ipBin[i],2);
}else if (importantBlock==i) {
//the important block.
mask+=maskBlock;
maskBinary+=maskBinaryBlock;
netBinary+=netBlockBinary;
bcBinary+=bcBlockBinary;
net+=parseInt(netBlockBinary,2);
bc+=parseInt(bcBlockBinary,2);
rangeA+=(parseInt(netBlockBinary,2)+1);
rangeB+=(parseInt(bcBlockBinary,2)-1);
}else {
//block after the important block.
mask+=0;
maskBinary+="00000000";
netBinary+="00000000";
bcBinary+="11111111";
net+="0";
bc+="255";
rangeA+=0;
rangeB+=255;
}
//add . separator except the last block
if(i<4){
mask+=".";
maskBinary+=".";
netBinary+=".";
bcBinary+=".";
net+=".";
bc+=".";
rangeA+=".";
rangeB+=".";
}
}

//additional : count maximum host, maximum net and current subnets
var binaryHost="";
for(var i=(31-cidr);i>=0;i--){
binaryHost=binaryHost+"1";
}
var maxHost=parseInt(binaryHost,2);
var binarySubnet="";
for(var i=cidr;i>=0;i--){
binarySubnet=binarySubnet+"1";
}
var maxSubnet=parseInt(binarySubnet,2);
var binaryCurrentSubnetBlock="";
for(var i=maskBinaryBlockCount;i>=0;i--){
binaryCurrentSubnetBlock=binaryCurrentSubnetBlock+"1";
}
var maxCurrentSubnetBlock=parseInt(binaryCurrentSubnetBlock,2);

//write the results to the page.
document.getElementById('resMask').innerHTML=mask;
document.getElementById('resNet').innerHTML=net;
document.getElementById('resBC').innerHTML=bc;
document.getElementById('resRange').innerHTML=rangeA + " - " + rangeB;
document.getElementById('resBinIP').innerHTML=ipBin[1]+"."+ipBin[2]+"."+ipBin[3]+"."+ipBin[4];
document.getElementById('resBinMask').innerHTML=maskBinary;
document.getElementById('resBinNet').innerHTML=netBinary;
document.getElementById('resBinBC').innerHTML=bcBinary;
document.getElementById('resClass').innerHTML=standartClass;
document.getElementById('resSubnetId').innerHTML=cidr;
document.getElementById('resMaxHost').innerHTML=maxHost+" possible host(s) in current subnet";
document.getElementById('resMaxNet').innerHTML=maxSubnet+" of total possible subnet, "+maxCurrentSubnetBlock+" possible subnet in current block";
document.getElementById('resImportantBlock').innerHTML=importantBlock;
}else{
alert("invalid value");
}

}
</script>
</html>
[/code]

8 comments :

Post a Comment