Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #define PORT 8080
- int main(void)
- {
- int master_sock;
- int sock;
- struct sockaddr_in address;
- int opt = 1;
- int addrlen = sizeof(address);
- char str[4096] = {0};
- // allocating socket
- if (!(master_sock = socket(AF_INET, SOCK_STREAM, 0))) {
- perror("\nERROR: SOCKET ALLOCATION FAILED\n");
- return 1;
- }
- // attaching socket to the port 8080
- if (setsockopt(master_sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
- perror("\nERROR: ATTACHING SOCKET TO THE PORT 8080 FAILED\n");
- return 1;
- }
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons(PORT);
- // bind
- if (bind(master_sock, (struct sockaddr*) &address, sizeof(address)) < 0) {
- perror("\nERROR: BIND FAILED\n");
- return 1;
- }
- // try to specify maximum of 3 pending connections for the master socket
- if (listen(master_sock, 3) < 0) {
- perror("\nERROR: LISTEN\n");
- return 1;
- }
- printf("listening on port 8080...\n");
- fflush(stdin);
- if ((sock = accept(master_sock, (struct sockaddr*) &address, (socklen_t*) &addrlen)) < 0) {
- perror("\nERROR: ACCEPT FAILED\n");
- return 1;
- }
- printf("connection accepted!\n");
- fflush(stdout);
- close(0);
- dup(sock);
- while (1) {
- scanf("%s", str);
- printf("%s", str);
- fflush(stdout);
- }
- return(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement