-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathKSocket.cpp
More file actions
79 lines (70 loc) · 1.76 KB
/
Copy pathKSocket.cpp
File metadata and controls
79 lines (70 loc) · 1.76 KB
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
#include "KSocket.h"
#include <unistd.h> // close
#include "KInetAddress.h"
#include <string.h> // memset
using namespace kb;
void kb::setNonBlockAndCloseOnExec(int sockfd)
{
// non-block
int flags = ::fcntl(sockfd, F_GETFL, 0);
flags |= O_NONBLOCK;
int ret = ::fcntl(sockfd, F_SETFL, flags);
// close-on-exec
flags = ::fcntl(sockfd, F_GETFD, 0);
flags |= FD_CLOEXEC;
ret = ::fcntl(sockfd, F_SETFD, flags);
}
int kb::createTcpSocket()
{
int sockfd = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
{
std::cout << "LOG_SYSFATAL: "
<< "Socket::createTcpSocket" << std::endl;
}
return sockfd;
}
Socket::~Socket()
{
if (::close(sockfd_) < 0)
{
std::cout << "LOG_SYSERR: "
<< "Socket::close" << std::endl;
}
}
void Socket::bindAddress(const InetAddress &localaddr)
{
struct sockaddr_in myaddr = localaddr.getSockAddrInet();
int ret = ::bind(sockfd_, (sockaddr *)&myaddr, sizeof myaddr);
if (ret < 0)
{
std::cout << "LOG_SYSFATAL: "
<< "Socket::bindAddress" << std::endl;
}
}
void Socket::listen()
{
int ret = ::listen(sockfd_, SOMAXCONN);
if (ret < 0)
{
std::cout << "LOG_SYSFATAL: "
<< "Socket::listen" << std::endl;
}
}
// 完成accpet
int Socket::accept(InetAddress *peeraddr)
{
struct sockaddr_in caddr; // client addr
socklen_t caddr_len = sizeof caddr;
memset(&caddr, 0, caddr_len);
int connfd = ::accept(sockfd_, (struct sockaddr *)&caddr, &caddr_len);
if (connfd < 0)
{
std::cout << "LOG_SYSERR: " << "Socket::accept" << std::endl;
}
if(connfd >= 0)
{
peeraddr->setSockAddrInet(caddr);
}
return connfd;
}