forked from skyfireitdiy/sflib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsf_tcp_utils.h
95 lines (80 loc) · 2.08 KB
/
sf_tcp_utils.h
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
94
95
/**
* @version 1.0.0
* @author skyfire
* @mail [email protected]
* @see http://github.com/skyfireitdiy/sflib
* @file sf_tcputils.h
* sflib第一版本发布
* 版本号1.0.0
* 发布日期:2018-10-22
*/
#pragma once
#ifdef _WIN32
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <vector>
#include <cassert>
#include <cstring>
#include <string>
#include "sf_type.hpp"
#include "sf_define.h"
namespace skyfire
{
#pragma pack(1)
/**
* @brief 包头
*/
struct sf_pkg_header_t
{
unsigned char checksum; // 校验和
int type; // 包类型
size_t length; // 包长度
};
#pragma pack()
/**
* 生成数据包
* @tparam T 数据类型
* @param data 数据
* @return 二进制数据包
*/
template<typename T>
typename std::enable_if<std::is_pod<T>::value, byte_array>::type make_pkg(const T &data);
/**
* 解析数据包
* @tparam T 数据类型
* @param data 数据
* @return 解析出来的数据包
*/
template<typename T>
typename std::enable_if<std::is_pod<T>::value, T>::type take_pkg(const byte_array &data);
/**
* 计算header的校验和
* @param header 包头
*/
inline void make_header_checksum(sf_pkg_header_t& header);
/**
* 校验header的校验和
* @param header 包头
* @return 是否通过校验
*/
inline bool check_header_checksum(const sf_pkg_header_t& header);
/**
* 64位整型网络字节序转主机字节序
* @param input 整型数字(网络字节序)
* @return 整型数字(主机字节序)
*/
inline unsigned long long sf_ntoh64(unsigned long long input);
/**
* 64位整型主机字节序转网络字节序
* @param input 整型数字(主机字节序)
* @return 整型数字(网络字节序)
*/
inline unsigned long long sf_hton64(unsigned long long input);
}