You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.3 KiB
83 lines
2.3 KiB
2 years ago
|
#include "webserv.hpp"
|
||
|
|
||
|
Sock6::Sock6(listen_t listen) : Socket(listen) { _type = AF_INET6; }
|
||
|
|
||
|
int Sock6::launch() {
|
||
|
int opt = 1;
|
||
|
string ip = _listen.ip;
|
||
|
int port = _listen.port;
|
||
|
|
||
|
_addr6.sin6_family = AF_INET6;
|
||
|
inet_pton(AF_INET6, ip.c_str(), (void *)&(_addr6.sin6_addr.s6_addr));
|
||
|
_addr6.sin6_port = htons(port);
|
||
|
_master_socket = socket(_addr6.sin6_family, SOCK_STREAM, 0);
|
||
|
|
||
|
if (_master_socket == 0) {
|
||
|
cout << "Socket creation: " << strerror(errno) << "\n";
|
||
|
return (EXIT_FAILURE);
|
||
|
}
|
||
|
int opt_ret = setsockopt(_master_socket, SOL_SOCKET, SO_REUSEADDR,
|
||
|
(char *)&opt, sizeof(opt));
|
||
|
if (opt_ret < 0) {
|
||
|
cout << "Sockopt: " << strerror(errno) << "\n";
|
||
|
return (EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
if (bind(_master_socket, (struct sockaddr *)&_addr6, sizeof(_addr6)) < 0) {
|
||
|
cout << "Bind: " << strerror(errno) << "\n";
|
||
|
return (EXIT_FAILURE);
|
||
|
}
|
||
|
cout << "Listener " << ip << " on port " << port << "\n";
|
||
|
|
||
|
if (listen(_master_socket, 3) < 0) {
|
||
|
cout << "Listen: " << strerror(errno) << "\n";
|
||
|
return (EXIT_FAILURE);
|
||
|
}
|
||
|
cout << "Socket::_master_socket: " << _master_socket << "\n";
|
||
|
if (_master_socket < _min_fd)
|
||
|
_min_fd = _master_socket;
|
||
|
_amount++;
|
||
|
return (EXIT_SUCCESS);
|
||
|
}
|
||
|
|
||
|
void Sock6::refresh(Env *env) {
|
||
|
|
||
|
std::vector<int>::iterator it;
|
||
|
int valread;
|
||
|
int addrlen = sizeof(_addr6);
|
||
|
char buffer[10000];
|
||
|
if (FD_ISSET(_master_socket, &_readfds)) {
|
||
|
int new_socket = accept(_master_socket, (struct sockaddr *)&_addr6,
|
||
|
(socklen_t *)&addrlen);
|
||
|
if (new_socket < 0) {
|
||
|
cout << "Accept: " << strerror(errno) << "\n";
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
#ifdef __APPLE__
|
||
|
fcntl(new_socket, F_GETNOSIGPIPE);
|
||
|
#endif
|
||
|
cout << "New connection, socket fd is "
|
||
|
<< new_socket
|
||
|
// << ", ip is : " << inet_ntoa(_addr6.sin6_addr)
|
||
|
<< ", port : " << ntohs(_addr6.sin6_port) << "\n";
|
||
|
_clients.push_back(new_socket);
|
||
|
}
|
||
|
for (it = _clients.begin(); it < _clients.end(); it++) {
|
||
|
if (FD_ISSET(*it, &_readfds)) {
|
||
|
valread = read(*it, buffer, 10000);
|
||
|
if (valread == 0) {
|
||
|
getpeername(*it, (struct sockaddr *)&_addr6,
|
||
|
(socklen_t *)&addrlen);
|
||
|
// cout << "Host disconnected, ip " <<
|
||
|
//inet_ntoa(_addr6.sin6_addr)
|
||
|
// << ", port " << ntohs(_addr6.sin6_port) << "\n";
|
||
|
close(*it);
|
||
|
_clients.erase(it);
|
||
|
} else {
|
||
|
buffer[valread] = '\0';
|
||
|
answer(env, *it, buffer);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|