Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/socket.h>
- #include <stdlib.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <signal.h>
- #include <limits.h>
- #include <sys/epoll.h>
- #include <fcntl.h>
- #include <unistd.h>
- volatile sig_atomic_t terminated = 0;
- void handle(int signum) {
- terminated = 1;
- }
- int create_local_server(in_port_t port) {
- in_addr_t addr = inet_addr("127.0.0.1");
- struct sockaddr_in hints = {
- .sin_family = AF_INET,
- .sin_addr.s_addr = addr,
- .sin_port = port
- };
- int host_socket = socket(AF_INET, SOCK_STREAM, 0);
- bind(host_socket, (struct sockaddr*) &hints, sizeof(hints));
- return host_socket;
- }
- void add_user_fd(int epoll_fd, int user_fd) {
- struct epoll_event event = {
- .events = EPOLLIN,
- .data = {.fd = user_fd}
- };
- epoll_ctl(epoll_fd, EPOLL_CTL_ADD, user_fd, &event);
- }
- void change_data(char* recv, int size, char* send) {
- for (int i = 0; i < size; i ++) {
- if ((recv[i] <= 'z') && (recv[i] >= 'a')) {
- send[i] = recv[i] + 'A' - 'a';
- } else {
- send[i] = recv[i];
- }
- }
- }
- int main(int argc, char* argv[]) {
- struct sigaction handler = {
- .sa_handler = handle
- };
- sigaction(SIGTERM, &handler, NULL);
- in_port_t port = htons(atoi(argv[1]));
- int host_socket = create_local_server(port);
- fcntl(host_socket, F_SETFL, fcntl(host_socket, F_GETFL) | O_NONBLOCK);
- int epoll_fd = epoll_create1(0);
- int users_num = 0;
- if (listen(host_socket, 20) >= 0) {
- char recv_data[BUFSIZ];
- char send_data[BUFSIZ];
- while (!terminated) {
- int user_socket = 0;
- while ((user_socket = accept(host_socket, NULL, NULL)) > 0) {
- add_user_fd(epoll_fd, user_socket);
- users_num++;
- }
- if (users_num == 0) {
- continue;
- }
- struct epoll_event event;
- epoll_wait(epoll_fd, &event, 1, -1);
- int user_fd = event.data.fd;
- int size_of_recv = 0;
- if ((size_of_recv = read(user_fd, &recv_data, sizeof(recv_data))) == 0){
- shutdown(user_fd, SHUT_RDWR);
- } else {
- printf("%s", recv_data);
- change_data(recv_data, size_of_recv, send_data);
- write(user_fd, send_data, size_of_recv);
- }
- }
- }
- close(host_socket);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment