Showing posts with label code-snippets. Show all posts
Showing posts with label code-snippets. Show all posts

Saturday, May 12, 2007

Finding out available FTP servers on LAN : Part 2

I talked about finding ftp servers on a LAN using nmap in a previous post. Well, looks like I got a better alternative to nmap. And what is it? Well its no great software.. its just a small 50 lines program that attempts to connect on port 21 to PCs on LAN. If you can connect, then this PC has an FTP server hosted on it... add it to the list. I takes about 1.5 minutes on my network to scan 8960 IPs.
I was surprised how such a small and simple program could outperform a giant GNU tool like nmap. Or may be I could not fine-tune nmap to my needs. Anyway, this is the exact fine-tuned nmap command I was using that takes about 3.7 minutes to scan a list of 8960 IPs:-

$ nmap -n -P0 -p 21 --max_rtt_timeout 100 --max_retries 0 -oG ftpLog.gnmap -iL IPs.txt

I also tried using min_parallelism option and min_hostgroup option but they didn't provide any speedup. May be some nmap expert could comment on it. One more thing to be said is that if remove -P0 option or in other words enable pinging .. it takes only 1.5 mins! A great improvement.. but it misses out some FTP servers(those whose firewall disable ping scanning). So I had no resort but to use my own program.
This is the program in case someone is interested:-

/*
* NetworkScanner.c
*
* A fast network scanner that scans for a specified open port.
*
* It is an enhanced version of propecia.c created by Troy Robinson
* Created : 02/05/2007
* Author : Sandeep Kumar aka Turbo : http://students.iiit.ac.in/~sandeep_kr
*
* Usage: ./a.out
* Examples of Ip in ipfile:-
* 172.16-31.*.*
* 192.168.36.200
* 172.*.*.*
* 172.16.0-255.0-255
*
* Sample Usage: ./a.out 21 255 IP_List.txt Out.txt
*
*/

#include
#include
#include
#include
#include
#include
#include
int ParseIPPart(char *ipPart, int n, int *s, int *e, int startCtr, int dashCtr);
int ParseIP(char *ip, int s[4], int e[4]);
int main (int argc, char *argv[])
{
if (argc <> \n", argv[0]);
printf("Examples of Ip in ipfile:-\n172.16-31.*.*\n192.168.36.200\n172.*.*.*\n172.16.0-255.0-255\n");
printf("Sample Usage: %s 21 255 IP_List.txt Out.txt\n",argv[0]);
exit(1);
}
int port = atoi(argv[1]); // Port to scan
int parallelLimit = atoi(argv[2]); // Max no. parallel processes (using fork)
char *fname = argv[3]; // input filename
char *outFname = argv[4]; // output filename
int procCtr = 0; // current count of parallel propcesses
char ip[20]; // scanned ip string from input file
int s[4],e[4]; //ip range as parsed from scanned ip string ip.
char host[16];
int i1,i2,i3,i4;
int sockfd, result;
struct sockaddr_in address;
FILE *fp = fopen(fname,"r");
if(fp==NULL)
{
perror("fopen");
exit(0);
}
FILE *fw = fopen(outFname,"w");
if(fw==NULL)
{
perror("fopen");
exit(0);
}
while(fscanf(fp," %s",ip)!=EOF)
{
if(ParseIP(ip,s,e)==-1)
{
fprintf(stderr,"Invalid IP Range: %s\n",ip);
continue;
}
//printf("Range is:%d-%d.%d-%d.%d-%d.%d-%d\n",s[0],e[0],s[1],e[1],s[2],e[2],s[3],e[3]);
for(i1=s[0];i1<=e[0];i1++)for(i2=s[1];i2<=e[1];i2++)for(i3=s[2];i3<=e[2];i3++)for(i4=s[3];i4<=e[3];i4++) { sprintf (host, "%d.%d.%d.%d", i1,i2,i3,i4); if(procCtr>=parallelLimit)
{
wait(NULL);
procCtr--;
}
int childPid = fork();
if(childPid>=0) // fork succeeded
{
if (childPid == 0) //child
{
address.sin_family = AF_INET;
address.sin_port = htons (port);
address.sin_addr.s_addr = inet_addr (host);
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if (sockfd < result =" connect" result ="="">0)
{
wait(NULL);
procCtr--;
}
close (sockfd);
exit(0);
}
// Parses one part of an IP. An IP has 4 parts separated by dots.
int ParseIPPart(char *ipPart, int n, int *s, int *e, int starCtr, int dashCtr)
{
int i,j;
if(starCtr) // For *
{
if(n!=1)return -1;
*s=0;*e=255;return 0;
}
if(dashCtr==0) // For normal number without star or dash
{
if(n==0||n>3)return -1;
*s=0;for(j=0;j255)return -1;
*e=*s;
return 0;
}
else if(dashCtr==1) // For dash
{
for(i=0;i3||n-1-i>3)return -1;
*s=0;for(j=0;j255)return -1;
*e=0;for(j=i+1;j255)return -1;
return 0;
}
else if(dashCtr>1) return -1;
}
// Parses an IP into the IP format: a-b.c-d.e-f.g-h
int ParseIP(char *ip, int s[4], int e[4])
{
int last=0,partCtr=0,starCtr=0,dashCtr=0,i;
for(i=0;1;i++)
{
if(ip[i]=='.'||ip[i]=='\0')
{
if(last==i || starCtr+dashCtr>1)return -1;
if(ParseIPPart(ip+last,i-last,&s[partCtr],&e[partCtr],starCtr,dashCtr)==-1)return -1;
starCtr=0,dashCtr=0;
last = i+1;
partCtr++;
if(ip[i]=='\0')break;
if(partCtr==4)return -1;
}
else if(isdigit(ip[i]));
else if(ip[i]=='*')starCtr++;
else if(ip[i]=='-')dashCtr++;
else return-1;
}
if(partCtr!=4)return -1;
return 0;
}

This could be used for scanning any port, not just FTP port(21). The comments in the code says all about the program.

PS: I wonder why Blogspot does not provide code tags. Users have asked for it since ages. But Blogger just ignores us all. Need to move to Wordpress.

Thursday, January 11, 2007

How to refresh a page that is not loaded?

First of let us understand the heading of my post ;) If a page is already loaded in the browser, there are several methods to refresh it. You will find them all over the internet.
For example, you can use:-

  1. <equiv="refresh" content="5">
  2. location.reload(true)
  3. javascript:history.go(0)
  4. etc.
However, consider a different scenario. I typed the url of a page "A" that requires login. Now the page will redirect you to the login page "B". After you login successfully, you will again be redirected to the actual page that you requested, that is page A. Now your browser knows from its cache, that when you earlier requested page A, it was redirected to page B. So it will now not send a request for page A to server. It will directly load the contents of page B instead! Now browser is doing correct by trying to save network bandwidth and by trying to reduce server load. But in our case its a problem.
Now you will ask this scenario happens in most of the sites and they all work perfectly fine. The reason is that in most of the sites, when they redirect you after successful login, to page A, they change the url of A a little bit. That is mostly you will find that after you login, there will be some sid, or username appended to the url. That concatenation makes this url not same a A and so browser loads it all over again and the site seems to be working fine.(though the site maker has no idea about all this and was just lucky).
But I have a site where the url of page A does not changes. There are some restrictions and the url of Page A has to remain exactly same. So how do I solve the problem? I searched all over net but couldn't find.(though there must be some solution). But right now I am using this method:-

<html>
<body onLoad="document.form1.submit();" >
Login successful. You are being redirected to the page requested by you.
<form method="post" action="URL of the page to redirect to" name="form1">
</form>
</body>
</html>

Note that the above thing will ask the browser to use POST method. And browser knows that pages fetched with POST method are dynamic and it can't rely on cache. So it won't rely on cache and ask a copy of the page again from the server. Thats it.

PS: Even if the urls are same, browser will sometimes fetch the new copy from the server. This is just my observation. Because in my lab, I had no problem with the simple redirection. But I found that at few other places the cache copy was being used. So I had to use the post method. I guess this all depends on browser settings and proxy settings.

PS: The above problem happened with me with my IIIT LAN Browser project.

Wednesday, December 20, 2006

Calculate nth fibonacci number in O(log(n))

I wrote this function that calculates nth fibonacci number in O(log(n)) time complexity and O(log(n)) space complexity. This is helpful when n is very large. You can't calculate nth fib iteratively when n is say 2^31. You need O(log(n)) or better algorithm for that. However the below function can't calculate 2^31th fib because it won't fit into long long. But my point now is to just present the implementation of O(log(n)) algo for small integers. It can be easily adapted to any integer(however large) if you have a BigInt library. I will try to write the BigInt version later when I get time.

The logic behind this algo is explained here. Note that this algo does not use any approximation. Its 100% accurate. The O(1) alogs available for this use approximation and MAY give wrong answers for some value of n.
Note that F(0)=0 and F(1)=1.


/*
* This function computes the nth fibonacci number in log(n) time and log(n) space complexity.
* This is helpful when we need to calculate fibonacci number where n is very large.
* Note that when n is large, fib(n) won't fit in integer.
* So essentially this function will have to be adapted for bigint.
*
* We assume F(0)=0 and F(1)=1.
*
* Note that this function does not use any approximation. Its 100% accurate.
*/
#include
#include
#include
#include
#include
using namespace std;
int Fibonacci(int n)
{
if(n<=1)return n;
int *nums=NULL,*values=NULL,ret,ctr,a,b,i;
nums = new int[int(ceil(4*log(n)))+4];
ctr=0;
nums[ctr++]=n;
for(i=0;i if(nums[i]>1)
{
if(nums[i]&1) // if odd
{
if(find(nums+i+1,nums+ctr,(nums[i]+1)/2)==nums+ctr)
nums[ctr++]=(nums[i]+1)/2;
if(find(nums+i+1,nums+ctr,(nums[i]+1)/2-1)==nums+ctr)
nums[ctr++]=(nums[i]+1)/2-1;
}
else // if even
{
if(find(nums+i+1,nums+ctr,nums[i]/2)==nums+ctr)
nums[ctr++]=nums[i]/2;
if(find(nums+i+1,nums+ctr,nums[i]/2-1)==nums+ctr)
nums[ctr++]=nums[i]/2-1;
}
}
values = new int[ctr];
for(i=ctr-1;i>=0;i--)
{
if(nums[i]<=1)values[i]=nums[i];
else if(nums[i]&1) // if odd
{
a=values[find(nums+i+1,nums+ctr,(nums[i]+1)/2)-nums];
b=values[find(nums+i+1,nums+ctr,(nums[i]+1)/2-1)-nums];
values[i]=a*a+b*b;
}
else // if even
{
a=values[find(nums+i+1,nums+ctr,nums[i]/2)-nums];
b=values[find(nums+i+1,nums+ctr,nums[i]/2-1)-nums];
values[i]=(2*b+a)*a;
}
}
ret = values[0];
delete nums;
delete values;
return ret;
}
int main()
{
int n;
while(scanf(" %d",&n)!=EOF)
printf("%d\n",Fibonacci(n));
return 0;
}

Friday, November 03, 2006

Trim, ltrim, rtrim / strip, lstrip, rstrip fucntions for javascript

In programming, trim or strip is a string manipulation function or algorithm which removes leading and trailing whitespace from a string. ltrim removes only leading trailing whitespaces and rtrim removes only trailing whitespaces and trim removes both leading and trailing whitespaces.
Trim, ltrim and rtrim are also known as strip, lstrip and rstrip, respectively.

Javascript does not have its own trim or strip function. But you can define your own. Write the codes given below in your source code and you can use them as you do in other languages. Take care, that these codes should be written in your code before they are called.

trim:

String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "")
}
ltrim:
String.prototype.trim = function() {
return this.replace(/^\s*/g, "")
}
rtrim:
String.prototype.trim = function() {
return this.replace(/\s*$/g, "")
}
After writing the above codes you can use the functions normally. A few examples are:-
trimmed_str=str.trim();
trimmed_str=' someString '.trim();
str=str.ltrim();
str=str1.rtrim() + str2.rtrim();

TechnoratiTechnorati: , ,