You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
1.8 KiB
87 lines
1.8 KiB
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#include <sys/socket.h>
|
|
#include <stdlib.h>
|
|
#include <netinet/in.h>
|
|
#include <strings.h>
|
|
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
int main() {
|
|
|
|
int port = 5001;
|
|
struct sockaddr_in address;
|
|
int clilen = sizeof(address);
|
|
address.sin_family = AF_INET;
|
|
address.sin_addr.s_addr = INADDR_ANY;
|
|
address.sin_port = htons(port);
|
|
|
|
int socketHandler = socket(AF_INET, SOCK_STREAM, 0);
|
|
|
|
if (socketHandler == 0) {
|
|
|
|
printf("SOCKET FAILED!\n");
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
printf("SETUP SOCKET!\n");
|
|
}
|
|
int bindRes = bind(socketHandler, (struct sockaddr *)&address, sizeof(address));
|
|
if(bindRes < 0) {
|
|
|
|
printf("BIND FAILED! CODE: %d\n", bindRes);
|
|
|
|
} else {
|
|
|
|
printf("BINDED SOCKET!\n");
|
|
|
|
}
|
|
listen(socketHandler, 5);
|
|
while(1) {
|
|
|
|
int newsockfd = accept(socketHandler, (struct sockaddr *) &address, &clilen);
|
|
|
|
if (newsockfd < 0) {
|
|
|
|
printf("ERROR LISTENING!\n");
|
|
exit(1);
|
|
|
|
}
|
|
int pid = fork();
|
|
if (pid == 0) {
|
|
|
|
printf("NEW CLIENT!\n");
|
|
doprocessing(newsockfd);
|
|
exit(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
return 0;
|
|
} |