108 lines
1.6 KiB
C
108 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <unistd.h> // sleep
|
|
#include <pthread.h>
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <string.h>
|
|
|
|
#define PORT 8080
|
|
|
|
void *loop(){
|
|
|
|
while(1) {
|
|
sleep(1);
|
|
printf("testing\n");
|
|
}
|
|
}
|
|
|
|
int main(int argc, char *argv[]){
|
|
|
|
int server_handle;
|
|
if((server_handle = socket(AF_INET, SOCK_STREAM, 0)) < 0){
|
|
|
|
perror("Failed to create socket");
|
|
exit(1);
|
|
}
|
|
|
|
int opt = 1;
|
|
if(
|
|
setsockopt(
|
|
server_handle,
|
|
SOL_SOCKET,
|
|
SO_REUSEADDR | SO_REUSEPORT,
|
|
&opt,
|
|
sizeof(opt)
|
|
)
|
|
){
|
|
|
|
perror("Could not set socket options");
|
|
exit(1);
|
|
}
|
|
|
|
struct sockaddr_in address;
|
|
address.sin_family = AF_UNSPEC;
|
|
address.sin_addr.s_addr = INADDR_ANY;
|
|
address.sin_port = htons(PORT);
|
|
if(
|
|
(
|
|
bind(
|
|
server_handle,
|
|
(struct sockaddr*)&address,
|
|
sizeof(address)
|
|
)
|
|
) < 0
|
|
){
|
|
|
|
perror("Failed to bind to socket");
|
|
exit(1);
|
|
}
|
|
|
|
if(
|
|
listen(
|
|
server_handle,
|
|
3
|
|
) < 0
|
|
){
|
|
|
|
perror("Failed to listen to socket");
|
|
exit(1);
|
|
}
|
|
|
|
printf("[INFO] Listening for connections\n");
|
|
|
|
int client_handle;
|
|
socklen_t addrlen = sizeof(address);
|
|
//while(1){
|
|
|
|
if(
|
|
(
|
|
client_handle = accept(
|
|
server_handle,
|
|
(struct sockaddr*)&address,
|
|
&addrlen
|
|
)
|
|
) < 0
|
|
){
|
|
|
|
perror("Failed to accept client connection");
|
|
exit(1);
|
|
}
|
|
//}
|
|
|
|
ssize_t buffer_read;
|
|
|
|
while(1){
|
|
char buffer[1024] = {0};
|
|
buffer_read = read(client_handle, buffer, 1023);
|
|
|
|
printf("Message (%zd): %s", buffer_read, buffer);
|
|
send(client_handle, buffer, strlen(buffer), 0);
|
|
}
|
|
|
|
return 0;
|
|
/*
|
|
pthread_t thread_id;
|
|
pthread_create(&thread_id, NULL, loop, NULL);*/
|
|
//pthread_join(thread_id, NULL);
|
|
}
|