-
Notifications
You must be signed in to change notification settings - Fork 3
/
TcpSocket.h
134 lines (110 loc) · 2.85 KB
/
TcpSocket.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/************************************************
*
* file : TcpSocket.h
* author: bobding
* date : 2014-09-25
* detail:
*
************************************************/
#ifndef _TCPSOCKET_H_
#define _TCPSOCKET_H_
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include "Log.h"
class TcpSocket
{
public:
TcpSocket() : sockfd(-1)
{}
// return >=0 means success, otherwise failed.
int Open()
{
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
{
LogError("[Socket::Open] create socket failed: %s.\n", strerror(errno));
}
return sockfd;
}
// host: 127.0.0.1 or www.qq.com
// return 0 means success, otherwise failed.
int Connect(const char* host, unsigned short port)
{
if (sockfd < 0)
{
LogError("[Socket::Connect] invalid sockfd.\n");
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
struct hostent* h = gethostbyname(host);
if (0 == h)
{
LogError("[Socket::Connect] gethostbyname failed: %s.\n", strerror(errno));
return -1;
}
addr.sin_addr = *(struct in_addr*)h->h_addr_list[0];
int ret = connect(sockfd, (const struct sockaddr*)&addr, sizeof(addr));
if (ret < 0)
{
LogError("[Socket::Connect] connect failed: %s.\n", strerror(errno));
return -1;
}
return 0;
}
// return send bytes, -1 means failed.
int Send(const char* buffer, unsigned int length)
{
if (sockfd < 0)
{
LogError("[Socket::Send] invalid sockfd.\n");
return -1;
}
int ret = send(sockfd, buffer, length, 0);
if (ret < 0)
{
LogError("[Socket::Send] send failed: %s.\n", strerror(errno));
return -1;
}
return ret;
}
// return recv bytes, -1 means failed.
int Recv(char* buffer, unsigned int length)
{
if (sockfd < 0)
{
LogError("[Socket::Recv] invalid sockfd.\n");
return -1;
}
int ret = recv(sockfd, buffer, length, 0);
if (ret < 0)
{
LogError("[Socket::Recv] recv failed: %s.\n", strerror(errno));
return -1;
}
return ret;
}
// return 0 success, otherwise failed.
int Close()
{
int ret = close(sockfd);
if (ret < 0)
{
LogError("[Socket::Close] close socket failed: %s.\n", strerror(errno));
}
sockfd = -1;
return ret;
}
int GetSocket()
{
return sockfd;
}
private:
int sockfd;
};
#endif // _TCPSOCKET_H_