Skip to content

Instantly share code, notes, and snippets.

@s7ephen
Created March 20, 2012 19:09
Show Gist options
  • Save s7ephen/2139962 to your computer and use it in GitHub Desktop.
Save s7ephen/2139962 to your computer and use it in GitHub Desktop.
bfishchat_client
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h> /* memset() */
#include <sys/time.h> /* select() */
#define CHARPERLINE 512
#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100
void senddata (char tosend[1024], char destaddr[21]) {
int sd, rc;
struct sockaddr_in cliAddr, remoteServAddr;
struct hostent *h;
h = gethostbyname(destaddr);
if(h==NULL) {
printf("unknown host '%s' \n", destaddr);
exit(1);
}
remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,
h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);
/* socket creation */
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0) {
printf("cannot open socket \n");
exit(1);
}
/* bind any port */
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
if(rc<0) {
printf("cannot bind port\n");
exit(1);
}
rc = sendto(sd, tosend, strlen(tosend)+1, 0,
(struct sockaddr *) &remoteServAddr,
sizeof(remoteServAddr));
}
int main (int argc, char *argv[]) {
char text[CHARPERLINE];
char key[81], tmpkey[81];
char sendbuf[1024];
/* check command line args */
if(argc<2) {
printf("\nusage : %s <peer> || <peer2> \n", argv[0]);
exit(1);
}
if(argc>3) {
printf("\nusage : %s <peer> || <peer2> \n", argv[0]);
exit(1);
}
printf("\nPlease input the seed for the desired key ==> ");
fgets(key,81,stdin);
printf("\nPlease re-input the seed for the desired key ==> ");
fgets(tmpkey,81,stdin);
if (strcmp(key,tmpkey) != 0) {
printf("\nThose keys do not match...\nexiting.");
exit(1);
}
printf("\nOk, listening for input...type \"/quit\" to exit\n");
for (;;) {
FILE *fp=stdin;
fd_set readset;
FD_ZERO(&readset);
FD_SET(0, &readset); //FDSET IS VERY NECESSARY, otherwise the test cases below dont work!!!
/* Check for data on stdin */
if (FD_ISSET(fileno(fp), &readset)) {
memset(text, 0, sizeof(text));
if (!read(0, text, sizeof(text) - 1)) {
printf ("\n Exiting...\n");
return 0;
}
else {
//---------CONDITIONAL BLOCK FOR COMMANDS!
if(text[0] == '/') {
if(!strncmp(text,"/quit", 5)) {
printf("\n*** Exiting... ***\n");
return 0;
}
}
//encrypt data text[] --> sendbuf[];
strncpy(sendbuf,encrypt_string(key,text),sizeof(sendbuf)-1);
//new data send routine
senddata(sendbuf, argv[1]);
if (argc==3) { //IF ANOTHER IP WAS Specified, then send to it.
senddata(sendbuf, argv[2]);
}
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment