-
Notifications
You must be signed in to change notification settings - Fork 0
/
Socket-server.c
67 lines (53 loc) · 1.52 KB
/
Socket-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
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
int main() {
int listenfd = 0; // Socket file descriptor
int connfd = 0; // Accepted request file descriptor
int n = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];
int numrv;
// Instantiate the socket
listenfd = socket(AF_INET, SOCK_STREAM, 0);
printf("Success: Socket retrieved\n");
// Initialize structure and buffer
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
// Bind the server address to the socket
// aka "assigning a name to the socket"
bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
// Handle listening error
if (listen(listenfd, 10) == -1) {
printf("Failed to listen\n");
return -1;
}
// Accept a single awaiting request
connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);
strcpy(sendBuff, "Client has connected.\n");
write(connfd, sendBuff, strlen(sendBuff));
// Main loop
while (1) {
while ((n = read(connfd, sendBuff, sizeof(sendBuff) - 1)) > 0) {
sendBuff[n] = 0;
printf("Message received from %d: ", connfd);
fputs(sendBuff, stdout);
write(connfd, sendBuff, strlen(sendBuff));
}
if (n < 0) {
printf("\nRead error\n");
}
sleep(1);
}
close(connfd);
return 0;
}