From 034e571db6a3c85dc82b117a8328ed0c0ad5b671 Mon Sep 17 00:00:00 2001 From: ak0327 Date: Fri, 25 Aug 2023 09:56:57 +0900 Subject: [PATCH] add playground_socket --- .gitignore | 1 + playground/.gitignore | 5 +++ playground/playground_socket.cpp | 69 ++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 playground/.gitignore create mode 100644 playground/playground_socket.cpp diff --git a/.gitignore b/.gitignore index 3cebcd57..52a48286 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ !www !includes !test +!playground !*.cpp !*.hpp diff --git a/playground/.gitignore b/playground/.gitignore new file mode 100644 index 00000000..0da64b3b --- /dev/null +++ b/playground/.gitignore @@ -0,0 +1,5 @@ +* + +!.gitignore +!*.cpp +!*.hpp \ No newline at end of file diff --git a/playground/playground_socket.cpp b/playground/playground_socket.cpp new file mode 100644 index 00000000..8852f9f3 --- /dev/null +++ b/playground/playground_socket.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int test_socket(const char *server_ip, const char *server_port) { + int errcode; + int socket_fd; + int ai_family, ai_socktype, ai_protocol; + struct addrinfo *addr_info; + struct addrinfo hints = {}; +// const char *server_ip = "127.0.0.1"; +// const char *server_port = "65536"; + + printf("ip:%s, port:%s\n", server_ip, server_port); + + hints.ai_socktype = SOCK_STREAM; + hints.ai_family = AF_UNSPEC; // allows IPv4 and IPv6 + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV; // socket, IP, PORT + hints.ai_protocol = IPPROTO_TCP; + + errcode = getaddrinfo(server_ip, server_port, &hints, &addr_info); + if (errcode != 0) { + std::cerr << "[Error] getaddrinfo:" << gai_strerror(errcode) << std::endl; + return 1; + } +// std::cout << "errcode:" << errcode << ", " << + + ai_family = addr_info->ai_family; + ai_socktype = addr_info->ai_socktype; + ai_protocol = addr_info->ai_protocol; + errno = 0; + std::cout << "socket" << std::endl; + socket_fd = socket(ai_family, ai_socktype, ai_protocol); + if (socket_fd == -1) { + std::cerr << "[Error] socket:" << strerror(errno) << std::endl; + return 1; + } + + std::cout << "bind" << std::endl; + errno = 0; + if (bind(socket_fd, addr_info->ai_addr, addr_info->ai_addrlen) == -1) { + std::cerr << "[Error] bind:" << strerror(errno) << std::endl; + return 1; + } + + std::cout << "listen" << std::endl; + if (listen(socket_fd, SOMAXCONN) == -1) { + std::cerr << "[Error] listen:" << strerror(errno) << std::endl; + return 1; + } + + std::cout << "OK" << std::endl; + return 0; +} + +// port 0, 0はエラーにならない +int main() { + int ret1 = test_socket("255.255.255.254", "8080"); + int ret2 = test_socket("255.255.255.254", "8080"); + + std::cout << "ret1:" << ret1 << std::endl; + std::cout << "ret2:" << ret2 << std::endl; +}