Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <poll.h>
- #include "helper.h"
- #define PORT 8080
- #define MAX_CLIENTS 10
- int main() {
- int server_fd, new_socket, valread;
- struct sockaddr_in address;
- int opt = 1;
- int addrlen = sizeof(address);
- // Create socket
- if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
- perror("socket failed");
- exit(EXIT_FAILURE);
- }
- // Set socket options
- if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
- &opt, sizeof(opt))) {
- perror("setsockopt failed");
- exit(EXIT_FAILURE);
- }
- // Bind socket to port
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons(PORT);
- if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
- perror("bind failed");
- exit(EXIT_FAILURE);
- }
- // Listen for incoming connections
- if (listen(server_fd, MAX_CLIENTS) < 0) {
- perror("listen failed");
- exit(EXIT_FAILURE);
- }
- // Set up poll array
- struct pollfd fds[MAX_CLIENTS];
- fds[0].fd = server_fd;
- fds[0].events = POLLIN;
- int nfds = 1;
- // Wait for incoming connections and send message to client
- while (1) {
- if (poll(fds, nfds, -1) < 0) {
- perror("poll failed");
- exit(EXIT_FAILURE);
- }
- // Check for incoming connections
- if (fds[0].revents & POLLIN) {
- if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
- (socklen_t *)&addrlen)) < 0) {
- perror("accept failed");
- exit(EXIT_FAILURE);
- }
- // Add new socket to poll array
- fds[nfds].fd = new_socket;
- fds[nfds].events = POLLIN;
- nfds++;
- }
- // Check for data from clients
- for (int i = 1; i < nfds; i++) {
- if (fds[i].revents & POLLIN) {
- struct message msg = {1, "Hello, client!"};
- if (send(fds[i].fd, &msg, sizeof(msg), 0) == -1) {
- perror("send failed");
- exit(EXIT_FAILURE);
- }
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement