1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <limits.h>
#include <errno.h>
#define RED "\x1b[31m"
#define GRN "\x1b[32m"
#define YEL "\x1b[33m"
#define NRM "\x1b[0m"
//Defining Variables
//Starting Code
int main(int argc, char *argv[]) {
//defining things
int sock, newsock, portno, binder, listener;
ssize_t bytes_read, bytes_written, writeintro;
struct sockaddr_in serv_addr, cli_addr;
struct hostent *server;
int yes = 1;
socklen_t clilen;
//Check to make sure correct syntax
if(argc < 3) {
printf("\n%sUsage: <serveraddr> <portno>%s\n", RED, NRM);
exit(0);
};
//Make the socket!
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0 || sock == 0) {
printf("\n%s Unable to create the Socket.", RED);
};
//Define Ser.addr struct info
server = gethostbyname(argv[1]);
if(server == NULL) {
fprintf(stderr, "No such host.\n");
printf("%s\n", strerror(errno));
exit(EXIT_FAILURE);
};
portno = atoi(argv[2]);
serv_addr.sin_family = AF_INET;
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
//Bind on socket//Error it
binder = bind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if(binder < 0) {
printf("\n%sBinding Failed.%s", RED, NRM);
};
//Listen on Socket for Connection/Error it
listener = listen(sock, 20);
if(listener < 0) {
printf("\n%s Failed to listen!%s", RED, NRM);
};
fprintf(stdout, "%s Waiting for a connection...%s", GRN, NRM);
//Accept the Socket/Error it
newsock = accept(sock, (struct sockaddr *) &cli_addr, &clilen);
if(newsock < 0) {
printf("\n%sFailed to Accept the Connection%s", RED, NRM);
};
fprintf(stdout, "Connection!");
//On Connection (The Good Stuff)
//Recv first string (user) for broadcast.
ssize_t uname;
char data[155];
char format[155];
char joined[155] = "Connected on";
char *from = inet_ntoa(cli_addr.sin_addr);
ssize_t joinbcast;
//uname = read(newsock, data, sizeof(data));
//strcpy(data, format);
//strcat(format, joined);
//strcat(format, from);
//joinbcast = send(newsock, format, sizeof(format), 0);
for ( ; ;){
char *recved, *send;
ssize_t recvdata, senddata;
recvdata = read(newsock, recved, sizeof(recved));
if (recvdata == 0) {
printf("\n%sClient closed the connection%s\n", RED, NRM);
}
fprintf(stdout, "%s", recved);
senddata = write(newsock, recved, sizeof(recved));
};
close(newsock);
}
|