mirror of
https://github.com/Lizonghang/prima.cpp.git
synced 2025-09-10 18:14:34 +00:00
fix try_connect
This commit is contained in:
parent
d1b97f798e
commit
d6c8d322cd
8 changed files with 78 additions and 50 deletions
26
src/network-utils.cpp
Normal file
26
src/network-utils.cpp
Normal file
|
@ -0,0 +1,26 @@
|
|||
#include "network-utils.h"
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <unistd.h>
|
||||
|
||||
bool isPortOpen(const std::string& ip, uint32_t port, int timeout_sec) {
|
||||
int sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sock < 0) return false;
|
||||
|
||||
struct timeval tv;
|
||||
tv.tv_sec = timeout_sec;
|
||||
tv.tv_usec = 0;
|
||||
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||
|
||||
struct sockaddr_in server;
|
||||
server.sin_addr.s_addr = inet_addr(ip.c_str());
|
||||
server.sin_family = AF_INET;
|
||||
server.sin_port = htons(port);
|
||||
|
||||
int res = connect(sock, (struct sockaddr*)&server, sizeof(server));
|
||||
close(sock);
|
||||
return res == 0;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue