-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserver.c
66 lines (59 loc) · 1.39 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
//
// server.c
// simple_server
//
// Created by Injae Lee on 2014. 10. 10.
// Modified by Minsuk Lee,
// Copyright (c) 2014. Injae Lee All rights reserved.
// see LICENSE
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 3000
#define MAX_DATA 100
int main()
{
int ret = -1, rsize;
int serverSock;
int acceptedSock;
struct sockaddr_in Addr;
char readBuf[MAX_DATA];
socklen_t AddrSize = sizeof(Addr);
if ((serverSock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
goto leave;
}
Addr.sin_family = AF_INET;
Addr.sin_addr.s_addr = INADDR_ANY;
Addr.sin_port = htons(PORT);
if ((ret = bind(serverSock, (struct sockaddr *)&Addr, sizeof(Addr)))) {
perror("bind");
goto error;
}
if ((ret = listen(serverSock, 1))) {
perror("listen");
goto error;
}
acceptedSock = accept(serverSock, (struct sockaddr *)&Addr, &AddrSize);
if (acceptedSock == -1) {
perror("accept");
ret = -1;
goto error;
}
if ((rsize = recv(acceptedSock, readBuf, MAX_DATA, 0)) <= 0) {
perror("recv");
ret = -1;
} else {
printf("Read %d Bytes: '%s'\n", rsize, readBuf);
ret = 0;
}
close(acceptedSock);
error:
close(serverSock);
leave:
return ret;
}