Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <boost/endian/arithmetic.hpp>
- #include <boost/asio.hpp>
- namespace asio = boost::asio;
- namespace endian = boost::endian;
- int readVarInt(int32_t& output, unsigned char* buffer, size_t buflen)
- {
- output = 0;
- int v2 = 0;
- signed char v3;
- do
- {
- if (v2 >= buflen) break;
- v3 = buffer[v2];
- output |= (v3 & 127) << (v2++ * 7);
- if (v2 > 5) return v2;
- } while ((v3 & 128) == 128);
- return v2;
- }
- int writeVarInt(int32_t input, unsigned char* buffer)
- {
- int i = 0;
- while ((input & -128) != 0)
- {
- buffer[i++] = (input & 127) | 128;
- input >>= 7;
- }
- buffer[i++] = input;
- return i;
- }
- void writeVarIntToStream(std::ostringstream& stream, std::int32_t number)
- {
- unsigned char buffer[8];
- int len = writeVarInt(number, buffer);
- stream.write(reinterpret_cast<const char*>(buffer), len);
- }
- int main(int argc, char** argv)
- {
- if (argc != 3)
- {
- std::cerr << "Usage: host port";
- return 1;
- }
- std::string host(argv[1]);
- int port;
- try
- {
- port = std::stoi(argv[2]);
- }
- catch (std::exception&)
- {
- std::cerr<< "Invalid port number: " << argv[2];
- return 2;
- }
- std::ostringstream stream(std::ios::binary);
- writeVarIntToStream(stream, 0);
- writeVarIntToStream(stream, 210);
- writeVarIntToStream(stream, static_cast<int>(host.size()));
- stream.write(host.data(), host.size());
- endian::big_uint16_t portt(port);
- stream.write(reinterpret_cast<const char*>(&portt), 2);
- writeVarIntToStream(stream, 1);
- std::string fin = stream.str();
- stream.str("");
- writeVarIntToStream(stream, static_cast<int>(fin.size()));
- stream.write(fin.data(), fin.size());
- fin = stream.str();
- try
- {
- asio::io_service io;
- asio::ip::tcp::iostream con(host, std::to_string(port));
- con.expires_from_now(boost::posix_time::seconds(20));
- if (!con)
- std::cerr << "Error: " << con.error().message() << "\n";
- con << stream.str();
- std::string str;
- con >> str;
- }
- catch (std::exception& e)
- {
- std::cerr << e.what() << '\n';
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment