-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.cpp
More file actions
39 lines (35 loc) · 881 Bytes
/
utils.cpp
File metadata and controls
39 lines (35 loc) · 881 Bytes
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
// utils.cpp
#include "utils.h"
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h> // macOS 需要此头文件
uint32_t host_to_net(uint32_t x) {
return htonl(x); // 主机转网络(大端)
}
uint32_t net_to_host(uint32_t x) {
return ntohl(x); // 网络转主机
}
bool read_full(int fd, void* buf, size_t len) {
char* ptr = static_cast<char*>(buf);
while (len > 0) {
ssize_t n = read(fd, ptr, len);
if (n <= 0) {
return false; // 连接关闭或出错
}
ptr += n;
len -= n;
}
return true;
}
bool write_full(int fd, const void* buf, size_t len) {
const char* ptr = static_cast<const char*>(buf);
while (len > 0) {
ssize_t n = write(fd, ptr, len);
if (n <= 0) {
return false;
}
ptr += n;
len -= n;
}
return true;
}