Algorithm/network-connection/main.cpp

57 lines
1.4 KiB
C++
Raw Permalink Normal View History

#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <cstring>
using namespace std;
bool validate_addr(const string &addr) {
if (addr.size() > 22) return false;
int ip_parts[4];
int port;
sscanf(addr.c_str(), "%d.%d.%d.%d:%d", &ip_parts[0], &ip_parts[1], &ip_parts[2], &ip_parts[3], &port);
char out[35];
sprintf(out, "%d.%d.%d.%d:%d", ip_parts[0], ip_parts[1], ip_parts[2], ip_parts[3], port);
if (strlen(out) != addr.size()) return false; // Leading 0
if (port > 65536 || port < 0) return false;
for (int ip_part: ip_parts) {
if (ip_part > 256 || ip_part < 0) return false;
}
return true;
}
int main() {
int n;
map<string, int> servers;
cin >> n;
for (int i = 0; i < n; i++) {
string mode, t;
cin >> mode >> t;
if (!validate_addr(t)) {
cout << "ERR" << endl;
continue;
}
if (mode == "Server") {
if (servers.find(t) == servers.end()) {
// Not found, good to go
servers[t] = i + 1;
cout << "OK" << endl;
} else {
cout << "FAIL" << endl;
}
}
if (mode == "Client") {
if (servers.find(t) == servers.end()) {
cout << "FAIL" << endl;
} else {
cout << servers[t] << endl;
}
}
}
}