These classes are small wrappers around the low-level and non-portable BSD sockets implementation. They have small overhead, so you can use them even for delicate tasks
#include <iostream> #include <string> #include <socklibpp/sockaddr.h> using namespace std; using namespace socklibpp;
Now the program itself:
int main() { string a; cin >> a; addr_in ip; if (!ip.resolve(a)) cout << "Could not resolve " << a << endl; else cout << a << " resolved to " << ip << endl; }
Note that it prints the port ":0" at the end, that's normal behavior. Objects of type socklibpp::addr_in hold ip and port (used for TCP and UDP). The default constructor creates an invalid address with port 0; but you can set the address and port using the ip(), port(), resolve(), ip_port() and resolve_port() methods. It can also parse strings in ip:port and hostname:port formats.
Now a program that creates a socket, starts a connection, and sends a random number:
#include <iostream> #include <cstdlib> #include <socklibpp/sockbase.h> using namespace std; using namespace socklibpp; int main(int argc, char **argv) { if (argc<2) { cerr << "Missing address:port argument" << endl; return 1; } addr_in ip; if (!ip.resolve_port(argv[1])) { cerr << "Unknown or invalid host:port" << endl; return 1; } cout << "Connecting to " << ip << endl; sock s(sock::pf_inet, sock::sock_stream); if (!s.connect(ip)) { cerr << "Could not connect to " << ip << endl; return 1; } srand(time(0)); int x = rand(); s.send((const char*)&x, sizeof x); if (s.error) cerr << "Error sending: " << s.error << endl; s.close(); }
Here we see the same code from the previous example, to resolve the address. Then we create object of type socklibpp::sock; notice that the default constructor creates an invalid socket, so we need the non-default constructor, or use the create() method. The parameters pf_inet and sock_stream create the TCP/IP socket.
There are mainly 2 ways to test for errors in socket operations: if the method returns a boolean value, "true" means "success"; also, there's the public member "error" that contains the error associated with the socket, or zero if the operation was successful. I this example we see both kinds of tests: the boolean test for connect(), and the error test for send().
WARNING: socklibpp::sock objects don't close the connection automatically. They are just wrappers around the native socket interface, not high-level abstractions. That's why you have to call close() on them yourself.
See the examples page for more.