-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnetlibs.c
90 lines (74 loc) · 2.18 KB
/
netlibs.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
#include "netlibs.h"
int init_info(const char* port, struct addrinfo** serv) {
int status;
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((status=getaddrinfo(0, port, &hints, serv)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return status;
}
return 0;
}
int init_sock(const struct addrinfo *info) {
int sockfd, opt=1;
sockfd = socket(info->ai_family, info->ai_socktype, info->ai_protocol);
if(sockfd==-1) {
fprintf(stderr, "Fail to open socket\n");
return -1;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
fprintf(stderr, "Fail to set socket option\n");
}
if(bind(sockfd, info->ai_addr, info->ai_addrlen) == -1) {
fprintf(stderr, "Fail to bind port: %s\n", strerror(errno));
return -1;
}
if(listen(sockfd, BACKLOG_SIZE) == -1) {
fprintf(stderr, "Fail to listen on port: %s\n", strerror(errno));
return -1;
}
return sockfd;
}
int send_file(const char *file_path, const int sockfd) {
int len=0, read=0;
char rbuf[BUFFER_SIZE];
FILE *fp = 0;
memset(rbuf, 0, sizeof rbuf);
if ((fp=fopen(file_path,"r"))==0){
fprintf(stderr, "Could not open file: %s\n", file_path);
return -1;
}
while(!feof(fp) && (read=fread(rbuf, 1, BUFFER_SIZE, fp))) {
write_socket(rbuf, read, sockfd);
memset(rbuf, 0, sizeof rbuf);
len+=read;
}
fclose(fp);
return len;
}
int read_line(char *buf, const int sockfd) {
int stat = 0;
while(1) {
stat = read_socket(buf, 1, sockfd);
if(stat==0) return stat;
if(*buf=='\n') {
*buf = 0;
return stat;
}
++buf;
}
return stat;
}
int write_socket(const char *buf, const int len, const int sockfd) {
int sent = send(sockfd, buf, len, 0);
if(sent==-1) {
fprintf(stderr, "Send error\n");
}
return sent;
}
int read_socket(char *buf, int len, const int sockfd) {
return recv(sockfd, buf, len, 0);
}