Skip to content

Instantly share code, notes, and snippets.

@varqox
Last active January 3, 2017 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varqox/810c128e2704b2532575d1f90cbc475a to your computer and use it in GitHub Desktop.
Save varqox/810c128e2704b2532575d1f90cbc475a to your computer and use it in GitHub Desktop.
Scans ports in range to check which are available to use, you have to run it on the server side and the client side
#include <arpa/inet.h>
#include <csignal>
#include <poll.h>
#include <simlib/config_file.h>
#include <simlib/debug.h>
#include <simlib/filesystem.h>
#include <simlib/process.h>
#include <sys/resource.h>
// Krzysztof Małysa
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,n) for (int i = (a), i##__ = (n); i <= i##__; ++i)
#define REP(i,n) FOR(i,0,n-1)
#define FORD(i,a,n) for (int i = (a), i##__ = (n); i >= i##__; --i)
#define ALL(x) x.begin(), x.end()
#define EB emplace_back
#define ST first
#define ND second
#define OO(A) template<class... T> ostream& operator<<(ostream& os, const A<T...>& x) { return __o(os, ALL(x)); }
#define SZ(x) ((int)x.size())
typedef long long LL;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<PII> VPII;
template<class A, class B> ostream& operator<<(ostream&, const pair<A, B>&);
template<class I> ostream& __o(ostream&, I, I);
template<class T, size_t N> ostream& operator<<(ostream& os, const array<T, N>& x) { return __o(os, ALL(x)); }
OO(vector) OO(deque) OO(set) OO(multiset) OO(map) OO(multimap)
template<class A, class B> ostream& operator<<(ostream& os, const pair<A, B>& p) {
return os << "(" << p.ST << ", " << p.ND << ")";
}
template<class I> ostream& __o(ostream& os, I a, I b) {
os << "{";
for (; a != b;)
os << *a++, cerr << (a == b ? "" : " ");
return os << "}";
}
template<class I> ostream& __d(ostream& os, I a, I b) {
os << "{\n";
for (I c = a; a != b; ++a)
os << " " << distance(c, a) << ": " << *a << endl;
return os << "}";
}
template<class... T> void __e(T&&... a) {
int t[] = {(cerr << forward<T>(a), 0)...}; (void)t;
cerr << endl;
}
template<class A, class B> void mini(A& a, B&& b) { if (b < a) a = b; }
template<class A, class B> void maxi(A& a, B&& b) { if (b > a) a = b; }
int ceil2(int x) { return 1 << (sizeof(x) * 8 - __builtin_clz(x - 1)); }
#ifdef DEBUG
# define D(...) __VA_ARGS__
#else
# define D(...)
#endif
#define LOG(x) D(cerr << #x ": " << x)
#define LOGN(x) D(LOG(x) << endl)
#define DUMP(x) D(cerr << #x ": ", __d(cerr, ALL(x)) << endl)
#undef E
#define E(...) D(__e(__VA_ARGS__))
// #define endl '\n'
// constexpr char nl = '\n';
// End of templates
#if 0
#define SHOW_STATS(...) __VA_ARGS__
#include <unistd.h>
void show_stats() {
system(("cat /proc/" + to_string(getpid()) + "/status >&2").c_str());
}
#else
#define SHOW_STATS(...)
#endif
void my_listen(int socket_fd, const string& port) {
sockaddr_in name;
socklen_t client_name_len = sizeof(name);
char ip[INET_ADDRSTRLEN];
for (;;) {
// accept the connection
int client_socket_fd = accept(socket_fd, (sockaddr*)&name,
&client_name_len);
Closer closer(client_socket_fd);
if (client_socket_fd == -1)
continue;
// Wait for data
constexpr int POLL_TIMEOUT = 2 * 1000; // in milliseconds
pollfd pfd = {client_socket_fd, POLLIN, 0};
D(stdlog("peek(): polling... ");)
if (poll(&pfd, 1, POLL_TIMEOUT) <= 0) {
D(stdlog("peek(): No response");)
D(stdlog("No request");)
continue;
}
D(stdlog("peek(): OK");)
array<char, 1 << 10> buff;
ssize_t rc = read(client_socket_fd, buff.data(), buff.size());
D(stdlog("peek(): Reading completed; buff_size: ", toStr(rc));)
if (rc <= 0)
errlog("read()", error(errno));
// extract IP
inet_ntop(AF_INET, &name.sin_addr, ip, INET_ADDRSTRLEN);
stdlog("Connection accepted: ", port, " form ",
ip);
if (StringView(buff.data(), rc) == "Port check") {
stdlog("\033[1;32mPort available:\033[m ", port, "!!!");
return;
}
stdlog("Closing...");
closer.close();
stdlog("Closed");
}
}
int checkout_port(unsigned port) {
// SHOW_STATS(atexit(show_stats);)
// ios::sync_with_stdio(false);
// cin.tie(nullptr);
int socket_fd;
sockaddr_in name;
name.sin_family = AF_INET;
memset(name.sin_zero, 0, sizeof(name.sin_zero));
// Extract port from address
// unsigned port = 8881; // server port
// Set server port
name.sin_port = htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY); // server address
if ((socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
errlog("Failed to create socket", error(errno));
return 1;
}
int true_ = 1;
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &true_, sizeof(int))) {
errlog("Failed to setopt", error(errno));
return 2;
}
// Bind
constexpr int TRIES = 1;
for (int try_no = 1; bind(socket_fd, (sockaddr*)&name, sizeof(name));) {
errlog("Failed to bind (try ", toStr(try_no), ')', error(errno));
if (++try_no > TRIES)
return 3;
usleep(800000);
}
if (listen(socket_fd, 10)) {
errlog("Failed to listen", error(errno));
return 4;
}
stdlog("Listening on ", toStr(port));
my_listen(socket_fd, toStr(port).str);
sclose(socket_fd);
return 0;
}
int client(const string& address, unsigned port) {
int socket_fd;
/* Create the socket. */
socket_fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
/* Store the server’s name in the socket address. */
sockaddr_in name;
name.sin_family = AF_INET;
memset(name.sin_zero, 0, sizeof(name.sin_zero));
name.sin_port = htons(port);
// name.sin_addr.s_addr = htonl(INADDR_ANY); // server address
if (!(name.sin_addr.s_addr = inet_addr(address.data()))) {
errlog("Incorrect IPv4 address: `", address, '`', error(errno));
exit(8);
}
/* Connect the socket. */
if (connect (socket_fd, (struct sockaddr*)&name, sizeof(name))) {
errlog("Port ", toStr(port), ": failed to connect to server", error(errno));
return 1;
}
/* Write the text on the command line to the socket. */
string msg {"Port check"};
if (send(socket_fd, msg.data(), msg.size(), 0) != (ssize_t)msg.size()) {
errlog("Port ", toStr(port), ": failed to send the whole message", error(errno));
return 2;
}
stdlog("\033[1;32mMessage sent on port:\033[m ", toStr(port));
close(socket_fd);
return 0;
}
// How to use:
// Run `./xxx` min_port max_port on the server and
// Run `./xxx serv.ip.address` min_port max_port on the outside client
int main(int argc, char** argv) {
// Adjust soft limit to hard limit of file descriptors
struct rlimit limit;
(void)getrlimit(RLIMIT_NOFILE, &limit);
limit.rlim_cur = limit.rlim_max; // TODO: check out what happens when limit
// is reached
(void)setrlimit(RLIMIT_NOFILE, &limit);
vector<thread> threads;
// Run client
if (argc > 3)
FOR (port, atoi(argv[2]), atoi(argv[3]))
threads.emplace_back(client, argv[1], port);
// Run server
else
FOR (port, atoi(argv[1]), atoi(argv[2]))
threads.emplace_back(checkout_port, port);
for (auto&& thr : threads)
thr.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment