-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.cpp
More file actions
99 lines (86 loc) · 2.68 KB
/
Copy pathSocket.cpp
File metadata and controls
99 lines (86 loc) · 2.68 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// Created by george on 25.06.26.
//
#include <unistd.h>
#include <iostream>
#include <stdexcept>
#include <string>
#include "Socket.h"
namespace http {
Socket::Socket():
mSocket(INVALID_SOCKET),
mSocketAddress(),
mSocketAddressLength(0)
{
mSocket = ::socket(AF_INET, SOCK_STREAM, 0);
if (mSocket < 0)
{
throw std::runtime_error("Cannot create socket");
}
}
Socket::Socket(Socket&& other) noexcept:
Socket(other.mSocket, other.mSocketAddress, other.mSocketAddressLength)
{
other.mSocket = INVALID_SOCKET;
other.mSocketAddressLength = 0;
}
Socket::Socket(int socket, sockaddr_in const& socketAddress, unsigned int socketAddressLength) noexcept:
mSocket(socket),
mSocketAddress(socketAddress),
mSocketAddressLength(socketAddressLength)
{
}
Socket::operator sockaddr* () {
return reinterpret_cast<sockaddr*>(&mSocketAddress);
}
Socket::~Socket() {
close();
}
void Socket::bindToAddress(std::string const& address, int port) {
mSocketAddress.sin_family = AF_INET;
mSocketAddress.sin_addr.s_addr = inet_addr(address.c_str());
mSocketAddress.sin_port = htons(port);
if (int err = bind(mSocket, (sockaddr *)&mSocketAddress, sizeof(mSocketAddress)) < 0)
{
throw std::runtime_error("Cannot connect socket to address (error " + std::to_string(err) + ")");
}
mIPAddress = address;
mPort = port;
}
int Socket::listen(int backlog) {
if (isValid()) {
return ::listen(mSocket, backlog);
}
return -1;
}
Socket Socket::accept() {
sockaddr_in saddress;
socklen_t saddress_length = sizeof(saddress);
int acceptedSocket = ::accept(mSocket, (sockaddr *)&saddress, (socklen_t*)&saddress_length);
if (acceptedSocket < 0) {
throw std::runtime_error("Cannot accept connection from socket");
}
return Socket(acceptedSocket, saddress, saddress_length);
}
ssize_t Socket::receive(std::string& request) {
if (isValid()) {
char buffer[kBufferSize];
ssize_t readBytes = ::recv(mSocket, buffer, kBufferSize, 0);
buffer[readBytes] = '\0';
request = buffer;
return readBytes;
}
return -1L;
}
ssize_t Socket::send(std::string const& buffer) {
if (isValid()) {
return ::send(mSocket, buffer.c_str(), buffer.size(), 0);
}
return -1L;
}
void Socket::close(void) {
if (isValid()) {
::close(mSocket);
}
}
} // http