109 lines
2.8 KiB
C
Executable File
109 lines
2.8 KiB
C
Executable File
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
#include <unistd.h>
|
||
#include <sys/socket.h>
|
||
#include <fcntl.h>
|
||
#include <errno.h>
|
||
#include <netinet/in.h>
|
||
|
||
#include "errno.h"
|
||
#include "tools/log/log.h"
|
||
#include "http_rel.h"
|
||
|
||
|
||
int write_in_bk(char input,httpbuf* blk){
|
||
|
||
}
|
||
char *recv_http_request(int cfd){
|
||
|
||
}
|
||
|
||
|
||
/**
|
||
* @brief 初始化HTTP监听socket,所有错误通过logmanager记录
|
||
* @param port 监听端口
|
||
* @param logger 日志管理器实例指针
|
||
* @return 成功返回监听fd,失败返回-1并记录日志
|
||
*/
|
||
int init_http_network(int port, log_manager *logger)
|
||
{
|
||
|
||
int fd;
|
||
char log[MAX_LOG_LENGTH];
|
||
/* 1. 创建socket */
|
||
fd = socket(AF_INET, SOCK_STREAM, 0);
|
||
if (fd == -1) {
|
||
snprintf(log, sizeof(log),
|
||
"socket() failed: %s", strerror(errno));
|
||
logger->in_log(logger, log,"FATAL");
|
||
|
||
return -1;
|
||
}
|
||
|
||
/* 2. 设置SO_REUSEADDR,避免TIME_WAIT状态导致bind失败 */
|
||
int opt = 1;
|
||
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
|
||
snprintf(log, sizeof(log),
|
||
"setsockopt(SO_REUSEADDR) on fd=%d failed: %s",
|
||
fd, strerror(errno));
|
||
logger->in_log(logger,log,"ERROR:");
|
||
close(fd);
|
||
|
||
return -1;
|
||
}
|
||
|
||
/* 3. 设置为非阻塞模式(配合epoll使用) */
|
||
int flags = fcntl(fd, F_GETFL, 0);
|
||
if (flags == -1) {
|
||
|
||
snprintf(log, sizeof(log),
|
||
"fcntl(F_GETFL) on fd=%d failed: %s", fd, strerror(errno));
|
||
logger->in_log(logger,log,"ERROR:");
|
||
close(fd);
|
||
|
||
return -1;
|
||
}
|
||
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
|
||
snprintf(log, sizeof(log),
|
||
"fcntl(O_NONBLOCK) on fd=%d failed: %s", fd, strerror(errno));
|
||
logger->in_log(logger,log,"ERROR:");
|
||
close(fd);
|
||
|
||
return -1;
|
||
}
|
||
|
||
/* 4. 绑定到指定端口 */
|
||
struct sockaddr_in addr = {0};
|
||
addr.sin_family = AF_INET;
|
||
addr.sin_port = htons(port);
|
||
addr.sin_addr.s_addr = htonl(INADDR_ANY); // 监听所有网卡
|
||
|
||
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
|
||
snprintf(log, sizeof(log),
|
||
"bind(port %d) failed: %s (fd=%d)",
|
||
port, strerror(errno), fd);
|
||
logger->in_log(logger,log,"FATAL:");
|
||
close(fd);
|
||
|
||
return -1;
|
||
}
|
||
|
||
/* 5. 开始监听 */
|
||
if (listen(fd, 10) == -1) {
|
||
snprintf(log, sizeof(log),
|
||
"listen(fd=%d, backlog=10) failed: %s",
|
||
fd, strerror(errno));
|
||
logger->in_log(logger,log,"FATAL:");
|
||
close(fd);
|
||
|
||
return -1;
|
||
}
|
||
|
||
/* 6. 成功日志 */
|
||
snprintf(log, sizeof(log),
|
||
"Successfully listening on port %d (fd=%d)", port, fd);
|
||
logger->in_log(logger, log,"HTTP:");
|
||
return fd;
|
||
}
|