-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
93 lines (71 loc) · 2.23 KB
/
server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#define MAX (256)
#define PORT (60003)
void rec_and_print(int socket_fd){
char buff[MAX];
for (;;){
read(socket_fd, buff, sizeof(buff));
if( buff[0] == '\0'){
break;
}
printf("From client: %s \n", buff);
memset(buff,'\0',MAX);
}
}
int main(){
const char * addr = "127.0.0.1";
const struct sockaddr_in server_addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = inet_addr(addr),
.sin_port = htons(PORT)
};
struct sockaddr_in client;
int file_descriptor = socket(AF_INET,SOCK_STREAM,0);
if (file_descriptor == -1){
printf("Socket function failed \n");
} else{
printf("Socket created \n");
}
int bind_ret = bind(file_descriptor, (struct sockaddr *) &server_addr, sizeof(server_addr));
if (bind_ret == -1){
printf("Bind function failed \n");
} else {
printf("Socket bound \n");
}
int listen_ret = listen(file_descriptor, SOMAXCONN);
if (listen_ret == -1){
printf("Listen function failed \n");
} else {
printf("Socket listening \n");
}
socklen_t len_client = sizeof(client);
int accept_ret = accept(file_descriptor, (struct sockaddr *) &client, &len_client);
if (accept_ret == -1){
printf("Accept function failed \n");
} else{
char * client_addr;
struct in_addr ip = {
.s_addr = client.sin_addr.s_addr
};
printf("Connection from: (%s , %i) \n", inet_ntoa(ip), client.sin_port);
}
rec_and_print(accept_ret);
return 0;
}
/* bind - bind socket to address
* Sockaddr is a generic descriptor for any kind of socket operation,
* whereas sockaddr_in is a struct specific to IP-based communication
*/
/* listen - listen for incomming connection
SOMAXCONN tells the system to use the maximum backlog size for incoming connections.
Up to this value incoming connections are put in the backlog, when the value is reached,
connections are refused.
*/