#include #include #include #include #include #include /** * * socket struct for building sockets... * This will hold both listening sockets and connection sockets * TCP AND UDP! * */ typedef struct Socket { int socketfd; //socket id int client_socketfd; // this is the int you get when you call accept() int port; // port information struct sockaddr_in address; // sockaddr_in struct struct Socket *next; // next in the linked list } Socket; //head of the linked list of sockets struct Socket *_socket_head = NULL; /** * This is used by a thread to listen for incoming * connections * */ void doprocessing (int sock) { int n; char buffer[256]; bzero(buffer,256); while(1) { n = read(sock,buffer,255); if (n < 0) { perror("ERROR reading from socket"); exit(1); } printf("Here is the message: %s\n",buffer); n = write(sock,"I got your message",18); if (n < 0) { perror("ERROR writing to socket"); exit(1); } } } /** * * This function creates a listening function... * @params takes a an int for a port. * @return An active listening socket for incoming connections * */ Socket create_lsocket(int _port, int _connection_amount) { Socket *newSocket = malloc(sizeof(Socket)); //sockaddr_in struct stuff (making a new sockaddr_in and giving it details) struct sockaddr_in address; // make a struct of type sockaddr_in int addr_size = sizeof(address); // size of addess in decimal form // filling our struct with info address.sin_family = AF_INET; //ipv4.... address.sin_addr.s_addr = INADDR_ANY; // any local address I.E :0.0.0.0 address.sin_port = htons(_port); // htons takes a decimal number and converts it to network //this is a socket handler, like a file handler... int socketfd = socket(AF_INET, SOCK_STREAM, 0); // if the socks returns 0 then exit if (socketfd == 0) { printf("SOCKET FAILED!\n"); exit(1); } //lets bind that socket now int bindRes = bind(socketfd, (struct sockaddr *)&address, sizeof(address)); if(bindRes < 0) { printf("BIND FAILED! WITH CODE: %d\n", bindRes); exit(1); } listen(socketfd, 5); while(1) { int newsockfd = accept(socketfd, (struct sockaddr *) &address, &addr_size); if (newsockfd < 0) { printf("ERROR LISTENING!\n"); exit(1); } int pid = fork(); if (pid == 0) { printf("NEW CLIENT!\n"); doprocessing(newsockfd); exit(0); } } newSocket->socketfd = socketfd; newSocket->port = _port; newSocket->address = address; newSocket->next = NULL; // if the socket head is empty we are going to malloc the head and then start // the linked list of sockets if (_socket_head == NULL) { _socket_head = malloc(sizeof(Socket)); _socket_head->next = newSocket; } }