Tag Archives: code

My sysinfo program updated with new code. Even better than before!

http://www.securitronlinux.com/files/sysinfo.kdevelop-1.0.tar.gz.

This is the link to my newly updated sysinfo program. This has code added using the sysinfo struct. This means that the memory and uptime information that is output is actually readable now. This is what the output of the memory and uptime section looks like now.

homer@deusvult:~/Documents/sysinfo.kdevelop-1.0$ ./sysinfo 2
		Ram & swap information.
Filename				Type		Size	Used	Priority
/dev/sdb2                               partition	12287996	0	-1
/dev/sdb5                               partition	2559996	0	-2

System uptime : 0 days, 2:23:45
Total RAM   : 5900.9 MB
Free RAM   : 147.0 MB
Number of running processes : 368

Stackoverflow has been a great help in terms of getting this code to work.

Here is the code section in question. This outputs much more readable output. A great result.

	if (argc > 1 and strncmp(argv[1], "2", BUF) == 0) {
		printf("\t\tRam & swap information.\n");
		kernel("/proc/swaps", 2);

		/* This code from:
		 * http://stackoverflow.com/questions/14345937/sysinfo-returns-incorrect-value-for-freeram-even-with-mem-unit
		 */
		/* Conversion constants. */
		const long minute = 60;
		const long hour = minute * 60;
		const long day = hour * 24;
		const double megabyte = 1024 * 1024;

		/* Obtain system statistics. */
		struct sysinfo si;
		sysinfo (&si);

		/* Summarize interesting values. */
		printf ("System uptime : %ld days, %ld:%02ld:%02ld\n", 
		    si.uptime / day, (si.uptime % day) / hour, 
		    (si.uptime % hour) / minute, si.uptime % minute);
		printf ("Total RAM   : %5.1f MB\n", si.totalram / megabyte);
		printf ("Free RAM   : %5.1f MB\n", si.freeram / megabyte);
		printf ("Number of running processes : %d\n", si.procs);


	}

A nice sample of code that will render a spiral on your terminal screen. This could be useful indeed.

This code sample will render a spiral on your terminal when you compile and execute it. Very interesting indeed.

#include <sstream>
#include <iostream>
#include <string>

std::string rle =
"32 2@14 1n16 11@9 2@10 1n13 3@13 3@8 1@7 1n10 2@21 2@7 1@5 1n7 2@27 1@6 1@4 "
"1n6 1@10 10@10 2@5 2@2 1n4 2@7 4@9 4@9 1@5 1@2 1n3 2@6 3@15 3@8 1@5 1@1 1n3 "
"1@6 2@18 3@7 2@5 1@1n2 1@6 2@20 3@7 1@5 1@1n2 1@5 2@21 3@7 1@5 1@1n1 2@5 2@2"
"1 3@7 1@5 1@1n1 2@5 2@11 3@6 3@8 1@5 1@1n2 1@5 2@11 11@8 2@5 1@1n2 1@6 2@11 "
"8@9 2@5 1@1 1n3 1@6 2@26 2@5 2@1 1n3 2@6 2@24 2@5 2@2 1n4 2@6 3@20 2@6 2@3 1"
"n6 1@8 3@14 3@7 1@5 1n7 2@9 13@9 2@6 1n9 2@27 1@9 1n12 3@19 3@11 1n16 5@7 4@"
"16 1n22 5@21 1n";

int main()
{
	std::stringstream ss(rle);
	while (!ss.eof())
	{
		int n = 0;
		while (ss.peek() >= '0' && ss.peek() <= '9')
		n = n * 10 + ss.get() - '0';
		char c = ss.get();
		while (0 < n--)
			std::cout << (c != 'n' ? c : 'n');
		}
}

Very cool code that prints a tick sign in asterisks. This is awesome C++ code.

This code prints out a tick sign using asterisks. I tested this code on Fedora 19 and gcc 4.8 and it compiles without any problems.

#include <iostream>
#include <iomanip>

using std::cout;

int main() {

	cout<<std::setw(8)<<"*"<<"n";
	cout<<std::setw(7)<<"*"<<"n";
	cout<<std::setw(6)<<"*"<<"n";

	cout<<"*  *"<<"n"<<"* *"<<"n"<<"*";
	cout<< "n";

	return 0;
}

This is what you should get when you compile and run this code sample.

homer@neo $ ./loop 
       *
      *
     *
*  *
* *
*

Very cool indeed.

Ralph using a computer.

Useful code snippets and commands for Linux.

Alternatives to the ping and traceroute commands on a Linux system.

There are many alternatives to the ping and traceroute commands on a Linux system. The mtr command is one of them. This command will trace the route the network packets are taking to the target IP address.

bash 06:42:02 Mon Jul 22 [homer@deep-thought $ mtr 8.8.8.8

This code will ping a server and use tcp, udp, icmp, stream, and syn packets to do so. This is useful to see if a server is up, but they block icmp packets, this script will work regardless of this and still allow you to see if the server is up or not. Good if you are behind a proxy at a college or something like that. There is also a tcpping command for Linux that can work when you are behind a restrictive firewall. There is some information about this here: http://xmodulo.com/2013/01/how-to-install-tcpping-on-linux.html.

#!/usr/bin/perl

use warnings;
use strict;

use Net::Ping;

# code source: http://www.perlmonks.org/?node_id=943892
# More: http://stackoverflow.com/questions/3960595/how-can-i-ping-a-host-with-a-perl-one-liner-with-netping

#$| = 1;
print "Please type a host to check: -:\n";
my $host = <>; #Reading input from STDIN.

if (length($host) < 3) {
    print "You did not type a host!\n";
    exit(0);
}

my @proto = ("tcp", "udp", "icmp", "stream", "syn");

foreach my $pro ( @proto ) {
    print "#-Protocol $pro \n";
    my $p = Net::Ping->new($pro);
    chomp($host);
    # Specify source interface of pings
    print "$host is ";
    print "NOT " unless $p->ping($host, 2);
    print "reachable.\n";
    $p->close();
}

exit(0);

This is a good alternative for tracing the route taken from one host to another.

homer@deep-thought ~ % sudo tcptraceroute 127.0.0.1
[sudo] password for homer: 
traceroute to 127.0.0.1 (127.0.0.1), 30 hops max, 60 byte packets
 1  localhost (127.0.0.1) <syn,ack>  0.031 ms  0.004 ms  0.005 ms

This is how to ping the TCP port of a remote host. This is using the netcat tool.

homer@deep-thought ~ % nc -zvv yahoo.cn 80
Connection to yahoo.cn 80 port [tcp/http] succeeded!

The hping3 command on Linux Mint 15 is very useful for sending TCP packets to a remote host to test the configuration of the server.

Type this command to install this utility: sudo apt-get install hping3.

And this is the output you get when you are pinging the Yahoo website with hping3.

bash 09:32:38 Mon Jul 22 [homer@deep-thought $ sudo hping3 -S -p 80 yahoo.com
HPING yahoo.com (eth1 206.190.36.45): S set, 40 headers + 0 data bytes
len=46 ip=206.190.36.45 ttl=112 id=51335 sport=80 flags=SA seq=0 win=8192 rtt=208.4 ms
len=46 ip=206.190.36.45 ttl=110 id=53804 sport=80 flags=SA seq=1 win=8192 rtt=197.2 ms
len=46 ip=206.190.36.45 ttl=110 id=56362 sport=80 flags=SA seq=2 win=8192 rtt=211.5 ms
len=46 ip=206.190.36.45 ttl=110 id=58939 sport=80 flags=SA seq=3 win=8192 rtt=211.0 ms
len=46 ip=206.190.36.45 ttl=110 id=61474 sport=80 flags=SA seq=4 win=8192 rtt=197.5 ms
len=46 ip=206.190.36.45 ttl=112 id=64019 sport=80 flags=SA seq=5 win=8192 rtt=195.7 ms
len=46 ip=206.190.36.45 ttl=112 id=998 sport=80 flags=SA seq=6 win=8192 rtt=194.8 ms
len=46 ip=206.190.36.45 ttl=112 id=3556 sport=80 flags=SA seq=7 win=8192 rtt=210.2 ms
len=46 ip=206.190.36.45 ttl=112 id=6243 sport=80 flags=SA seq=8 win=8192 rtt=210.6 ms
len=46 ip=206.190.36.45 ttl=110 id=8839 sport=80 flags=SA seq=9 win=8192 rtt=197.2 ms
^C
--- yahoo.com hping statistic ---
10 packets transmitted, 10 packets received, 0% packet loss
round-trip min/avg/max = 194.8/203.4/211.5 ms
Ralph using a computer.

Ralph using a computer.

Wrapping the printf() statement onto multiple lines in C and some other useful samples.

This code sample shows how we are wrapping a printf() statement onto multiple lines using backslashes.

#include "stdio.h"

#define hello "Hello World."

int main(int argc, char* argv[])
{
	printf("This is a very long sentence we are handing down\n"\
		   "Mr smith, do you have anything to say for yourself"\
		   "?");

	printf("%s\n", hello);

	return 0;
}

This is the most obfuscated version of the C “Hello World” program that I could find.

#include 

#define e 3
#define g (e/e)
#define h ((g+e)/2)
#define f (e-g-h)
#define j (e*e-g)
#define k (j-h)
#define l(x) tab2[x]/h
#define m(n,a) ((n&(a))==(a))

long tab1[] = { 989L, 5L, 26L, 0L, 88319L, 123L, 0L, 9367L };
int tab2[] = { 4, 6, 10, 14, 22, 26, 34, 38, 46, 58, 62, 74, 82, 86 };

main(m1, s)
char *s;
{
	int a, b, c, d, o[k], n = (int)s;
	if (m1 == 1) {
		char b[2 * j + f - g];
		main(l(h + e) + h + e, b);
		printf(b);
	} else
		switch (m1 -= h) {
		case f:
			a = (b = (c = (d = g) << g) << g) << g;
			return (m(n, a | c) | m(n, b) | m(n, a | d) |
				m(n, c | d));
		case h:
			for (a = f; a < j; ++a)
				if (tab1[a] && !(tab1[a] % ((long)l(n))))
					return (a);
		case g:
			if (n < h)
				return (g);
			if (n < j) {
				n -= g;
				c = 'D';
				o[f] = h;
				o[g] = f;
			} else {
				c = '\r' - '\b';
				n -= j - g;
				o[f] = o[g] = g;
			}
			if ((b = n) >= e)
				for (b = g << g; b < n; ++b)
					o[b] = o[b - h] + o[b - g] + c;
			return (o[b - g] % n + k - h);
		default:
			if (m1 -= e)
				main(m1 - g + e + h, s + g);
			else
				*(s + g) = f;
			for (*s = a = f; a < e;)
				*s = (*s << e) | main(h + a++, (char *)m1);
		}
}

This is a program that writes to a text file. You are of course free to use this code in your own projects.

#include 
#include 

#define EQ ==
#define log "hello.txt"

int main(int argc, char *argv[]) {

	int x;

	x = 0;

	FILE *f;
	char Kyo[40];
	int Fsize;
	f = fopen(log, "w");
	Fsize = sizeof(f);
	if(!f) {
		printf("Sorry, I cannot open: %s.\n", log);
		exit(1);
	} else {

		while (x < 100) {
			fprintf(log,"*");
			if (x EQ 50) {
				fprintf(log,"-\n-");
			}
		x++;

		}
		fprintf(log, "\n\x78*----* Done. *----*\x78\n");
	}
	fclose(f);

	return 0;
}

Miscellaneous Perl programming information. How to use for loops and printing HTML properly.

Opening a folder and listing the contents, and not listing certain files. This is the Perl code I was using on my very old Tripod.com website.

opendir(DNAME, "$folder") || die "I cannot open the requested directory $folder \n $!";
@dirfiles2 = readdir (DNAME);
@dirfiles2 = sort(@dirfiles2);
foreach $x2 (@dirfiles2) {
    if ($x2 eq ".") {
	$x2 = ' ';
    }
    if ($x2 eq "..") {
	$x2 = ' ';
    }
    if ($x2 =~ /REMOVED/) {
	$x2 = ' ';
    }
    if ($x2 eq ".cgiclean") { # What is this?
	$x2 = ' ' ;
    }
    if ($x2 eq ".htaccess") {
	$x2 = ' ';
    }
    if ($x2 eq "$archive") {
	print "\n";
    } else {
# Simple hack to weed out those annoying zero length() strings...
	if (length $x2 > 3) {
	    print "\n";
	}
    }
}

closedir(DNAME);

How to get the date and time with Perl scripting. All you need to do is print “$date”; and you are done.

my @Days = ('Sunday','Monday','Tuesday',
	    'Wednesday','Thursday','Friday',
	    'Saturday');
my @Mon1 = ('January','February','March',
	    'April','May','June',
	    'July','August','September',
	    'October','November','December');

my ($Sec,$Min,$Hour,$MDay,$Mon,$Year,$WkDay) = (localtime)[0,1,2,3,4,5,6];
$Year += 1900;
if($Sec < 10) {
    $Sec = "0$Sec"
};
if($Min < 10) {
    $Min = "0$Min"
};
if($Hour < 10) {
    $Hour = "0$Hour"
};

$date = "$Hour:$Min:$Sec - $Days[$WkDay] $MDay $Mon1[$Mon] $Year";

Here is an example showing how to do a for() loop in Perl.

for ( $i=  0; $i <  32; $i++) {
	print "*";
}

This comprehensive script will print a HTML page to the terminal when you run it. This is a good starter for writing a CGI script that will print out its own HTML. This is using the CGI.pm module. This also sets a cookie containing the date that expires in 3 days.

#!/usr/bin/perl

use CGI qw/:standard -nosticky/;
my $query = new CGI;

print $query->header(-type=>'text/html',
		     -expires=>'+3d',
		     -cookie=>$date,
		     -charset=>'UTF-8');

print $query->start_html(-title=>'CGI Viewblog CGI Script.',
			 -meta=>{'keywords'=>'Blog Doom2 Level Editing Linux Doom',
				 'copyright'=>'Copyright 2004 John Cartwright.',
				 'definition'=>'General Viewblog Script.',
				 'Appeal'=>'Wide',
				 'description'=>'CGI Viewblog Script.'},
			 -BGCOLOR=>'#FFFFFF',
			 -TEXT=>'#000000',
			 -LINK=>'#888fff');

print $query->h1("CGI HTML Script.\n");

print $query->p("This script prints HTML to the terminal.\n");

print $query->end_html;

Finally, this code will write some information to a log file.

open FILE, ">> log.txt" || die "I cannot open the file: log.txt:\n $!\n";
print FILE "Visited: $date\n";
if ($user_ref) {
    print FILE "Referrer URL: $user_ref.\n";
}
print FILE "Users Browser: $user_agent.--\n\n";
close FILE;

Useful old C code of mine. Might be useful for reference.

This is a nice little program I wrote ages ago.

/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

/********************************************************************
* Description:
* Author:  
* Created at: Wed Jan 19 13:06:21 EST 2011
* Computer: myhost
* System: Linux 2.6.33-ARCH on x86_64
*
* Copyright (c) 2011   All rights reserved.
*
********************************************************************/

#include 
#include 

#define format "At this time: %H:%M:%S"
#define text "OP is a Troll."

int lineofstars (void) {
	int x = 0;
	while (x < 64) {
		printf("*");
		x++;
		if (x == 31) {
			printf("<|>");
		} else if (x == 64) {
			printf("\n-\n");
		}
	}
	return 0;
}

int main (int argc, char** argv) {

	lineofstars();

	char *File;
	char String[60];
	struct tm *ptr;
	time_t tm;
	char length[60];

	tm = time(NULL);
	ptr = localtime(&tm);
	strftime(length, 100, format, ptr);

	File = "log.txt";
	snprintf(String, 100, "%s, %s\n", length, text);

	FILE *f;
	f = fopen (File, "a+");

	if (!f) {
		printf("Sorry, I cannot open the file %s.\n", File);
		return 0;
	}

	fprintf(f, String);

	fflush(stdout);
	fclose(f);

	return 0;
}

Miscellaneous programming tricks with C.

This is a very simple Hello World program in C.

int main() {
	write(1, "Hello World\n", 14);
}

Counting how long a text string is.

#include 
#include 
#define MSG "Hello Doctor, let's get back to the TARDIS!"
int main() {
int g;
g = strlen(MSG);
if (g < 1) {
printf("The string is not very long!\n");
} else {
printf("The length of the string `MSG' is: %i characters.\n", g);
}
return 0;
}

Code sample to check for a certain argument to a C program. using strncmp() to read from the argv[1], which is the first argument to the C program and checking if it contains the value “2″. And the value BUF sets the maximum length of the string expected.

if (argc > 1 and strncmp(argv[1], "2", BUF) == 0) {
	printf("\t\tRam & swap information.\n");
	kernel("/proc/swaps", 2);
	printf("-Uptime: ");
	kernel("/proc/uptime", 2);
	kernel("/proc/meminfo", 2);
}

More code from my sysinfo C program that reads in files and processes them accordingly.

#ifndef SYSINFO_H_
#define SYSINFO_H_

#define BUF 0x05

/*
 * Function prototypes. Sexy... And unlike on the show `24', function
 * prototypes have nothing to to with hard disk sectors!
 */

void kernel(char,int);

/*
 *  @brief  /proc file opener
 *  @param  File  An output stream.
 *  @param  len  A string length.
 *  @return  none.
 *  @pre  @a len must be a non-NULL int.
 * I hope this little function is not offending anyone. it is the only
 * way I could think to have a single function that would be able to 
 * load the different files quickly and without fuss. And it works just
 * fine, and that is what matters in the end.
 */

struct _kern1 {
	char *File;
	int len;
	char Kyo[40];
} *kern1 = (struct _kern1 *) 0x80;

void kernel(const char *File, int len)
{
	FILE *f;
	char Kyo[40];

	if (len > 10 or len < 2)
		return;

	f = fopen(File, "r");
	if(!f) {
		printf ("Sorry, I cannot open: %s.\n", File);
		printf("Please check your permissions with\n"		\
			"your supervisor. The feature may not\n"	\
			"be compiled and\\or enabled in your\n"		\
			"kernel version. Or a scsi device, eg,\n"	\
			"a USB drive may not be attached.\n");
		return;
	} else {
/* Based on sample code from:
 * www.koders.com/c/fid84CFEFBF311605F963CB04E0F84A2F52A8120F33.aspx
 * Specifically the section on parsing the /proc/version.
 */
		while (feof(f) != 1) {
			fgets(Kyo, len, f);
			if (strncmp(Kyo, "((", 1) == 0)
				printf ("\n-");
			if (strncmp(Kyo, "#", 1) == 0) {
				printf ("\nVersion: #");
			} else {
/*
 * This function is fast, owing to this i feel. especially with gcc 
 * 4.3.2 & glibc 2.5+. it is faster than using: printf (Kyo);
 */
				fprintf (stdout, "%s", Kyo);
			}
			fflush(stdout);
		}
	}
	fclose(f);
}

#endif /* sysinfo.h */

Linux kernel 3.3 released, including some Android code?


The Linux kernel 3.3 has been released and among other features that have been included, there is some code from Google Android included. This is an interesting development, this does not mean that you can run Angry Birds on a Debian or Linux Mint system, but this could lead to something cool in the future. The Linux kernel is a free kernel that makes up a free operating system called Linux. The whole operating system is sometimes called Linux, but Linux is only the kernel, you could build a UNIX operating system using the GNU Coreutils, gcc, and Xorg, but have a different kernel maybe one you developed with your own team of developers and then you could distribute that as something else. FreeBSD uses Coreutils, gcc and the same software available on Linux distributions like Ubuntu, but FreeBSD uses a different kernel and a different executable format. The FreeBSD kernel is available for Debian with Debian KFreeBSD, that is an interesting idea, I prefer the Linux kernel, the hardware support is pretty good now, the need for binary firmware will not go away anytime yet, but at least you have a reasonable expectancy that the WIFI dongle you have bought will work with Linux. Netgear is a good brand. I am having some problems with my Internet connection right now, but I am wanting to try Debian Stable again.

The Linux kernel is truly a massive achievement, it would have cost a staggering, amount if a major corporation had developed the Linux kernel instead of a worldwide network of kernel hackers that have helped develop the Linux kernel and get this kernel to the state that is right now. There are many devices in the world that are running the Linux kernel including the Android operating system that is using the Linux kernel to provide a Linux powered operating system, as an alternative to Symbian and IOS. The Apple Macintosh operating system is built on top of the Darwin UNIX operating system kernel, the Darwin kernel is free to download, the interface and software placed on top of the underlying UNIX kernel is what you are actually paying for. I downloaded the Darwin operating system ISO, burned it to a DVD  and tried to boot it on a PC, but it would not boot, I just got an error. I guess that I need the expensive hardware to run the Darwin operating system, but I could just run OpenBSD  or FreeBSD if I wanted a UNIX operating system to experiment with. FreeBSD has the standard Linux Gnome desktop, the Desktop BSD live disc has a nice desktop as well, but the BSD desktops are lacking GEM/KMS support at the moment, something we take for granted with Linux. But this is coming slowly but surely. I might consider switching to FreeBSD if they added V4l support as well.

My PHP code for my Linux pages index.

This code is on my http://securitron.securitronlinux.com page. It shows a random image and a random webpage link.
<?php
$time = strftime(“%A %d %B %Y. %r – %Z”);
srand(time(NULL));
$day = rand() % 6;
$string = sprintf(“<font size=\”2pt\”><p>Welcome to my website.</p>\n”);
$links = array(“BejArray” => array(“0″ => “perl_code.php”, “1″ => “psx_doom.php”,
“2″ => “cgi_code.php”, “3″ => “doom_wadfiles.php”,
“4″ => “my_linux_system_2.php”, “5″ => “linux_configs.php”,
“6″ => “my_linux_system.php”
));

echo $string;

switch($day) {
case 0:
$string2 = “Perl CGI Code”;
break;
case 1:
$string2 = “PSX Doom goodness”;
break;
case 2:
$string2 = “Misc programming code”;
break;
case 3:
$string2 = “My Doom wadfiles”;
break;
case 4:
$string2 = “My Linux system tips part 2″;
break;
case 5:
$string2 = “My Linux configuration tips”;
break;
case 6:
$string2 = “My Linux system tips part 1″;
break;
default:
$string2 = “Take pot luck”;
}

printf(“<p>Random page: <a href=%s>%s</a>.</p>\n”, $links["BejArray"][$day], $string2);
printf(“<p>Welcome to my GNU/Linux pages. Server time is: %s.</p></font>”, $time);
echo “<img src=\”maps/00$day.png\” width=\”320\” height=\”200\” alt=\”Random Doom screenshot.\” style=\”float:right;padding: 8px\”>”;

?>