94 lines
2.3 KiB
C++
94 lines
2.3 KiB
C++
#pragma once
|
|
|
|
#ifdef _WIN32
|
|
#include <winsock2.h>
|
|
#include <ws2tcpip.h>
|
|
#include <ws2bth.h>
|
|
#include <ws2def.h>
|
|
#include <windows.h>
|
|
#define in_addr_t ULONG
|
|
#elif __linux__
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/epoll.h>
|
|
#include <arpa/inet.h>
|
|
#include <fcntl.h>
|
|
#include <errno.h>
|
|
#include <netinet/in.h>
|
|
#include <sys/eventfd.h>
|
|
#define SOCKET int
|
|
#define INVALID_SOCKET -1
|
|
#define SOCKET_ERROR -1
|
|
#else
|
|
#error "이 플랫폼은 지원되지 않습니다."
|
|
#endif
|
|
|
|
#include <chrono>
|
|
|
|
void err_quit(const char *msg) {
|
|
char *msgbuf = strerror(errno);
|
|
fprintf(stderr, "[%s] %s\n", msg, msgbuf);
|
|
exit(1);
|
|
}
|
|
|
|
void err_display(const char *msg) {
|
|
char *msgbuf = strerror(errno);
|
|
fprintf(stderr, "[%s] %s\n", msg, msgbuf);
|
|
}
|
|
|
|
#define LISTENIP "::"
|
|
#define LISTENPORT 9010
|
|
#define BUFSIZE 100
|
|
|
|
int main(int argc, char *argv[]) {
|
|
WSADATA wsa;
|
|
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
|
|
err_quit("WSAStartup()");
|
|
return EXIT_FAILURE;
|
|
}
|
|
SOCKET listenSocket = socket(AF_INET6, SOCK_STREAM, 0);
|
|
if (listenSocket == INVALID_SOCKET) err_quit("socket()");
|
|
|
|
struct sockaddr_in6 serverAddr;
|
|
memset(&serverAddr, 0, sizeof(serverAddr));
|
|
serverAddr.sin6_family = AF_INET6;
|
|
inet_pton(AF_INET6, LISTENIP, &serverAddr.sin6_addr);
|
|
serverAddr.sin6_port = htons(LISTENPORT);
|
|
|
|
if (SOCKET_ERROR ==
|
|
bind(listenSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)))
|
|
err_quit("bind()");
|
|
if (SOCKET_ERROR == listen(listenSocket, SOMAXCONN)) err_quit("listen()");
|
|
|
|
SOCKET client_sock;
|
|
struct sockaddr_in6 client_addr;
|
|
socklen_t addr_len;
|
|
|
|
addr_len = sizeof(client_addr);
|
|
printf("Waiting for connection...\n");
|
|
client_sock =
|
|
accept(listenSocket, (struct sockaddr *)&client_addr, &addr_len);
|
|
if (client_sock == INVALID_SOCKET) err_quit("accept()");
|
|
printf("Connection established!\n");
|
|
|
|
char buf[BUFSIZE + 1];
|
|
|
|
while (2) {
|
|
int retVal = recv(client_sock, buf, BUFSIZE, 0);
|
|
if (retVal == SOCKET_ERROR)
|
|
err_display("recv()");
|
|
else if (retVal == 0)
|
|
break;
|
|
|
|
char ipv6str[INET6_ADDRSTRLEN];
|
|
inet_ntop(AF_INET6, &client_addr, ipv6str, sizeof(ipv6str));
|
|
buf[retVal] = '\0';
|
|
printf("[TCP/%s:%d] %s\n", ipv6str, ntohs(client_addr.sin6_port), buf);
|
|
|
|
if (SOCKET_ERROR == send(client_sock, buf, BUFSIZE, 0))
|
|
err_display("send()");
|
|
}
|
|
|
|
WSACleanup();
|
|
}
|