protohackers

My solutions to the protohackers.com challenges.
git clone git://henryandlizzy.uk/protohackers
Log | Files | Refs

inet.hpp (977B)


      1 #pragma once
      2 
      3 #include "fd.hpp"
      4 
      5 #include <sys/socket.h>
      6 #include <netinet/in.h>
      7 #include <netinet/tcp.h>
      8 #include <arpa/inet.h>
      9 #include <err.h>
     10 
     11 #include <iostream>
     12 
     13 namespace inet {
     14 
     15 descriptor listen(int type)
     16 {
     17 	struct sockaddr_in addr {sizeof addr, AF_INET, htons(1337), {INADDR_ANY}, {}};
     18 	int reuseaddr = 1;
     19 
     20 	descriptor incoming{::socket(AF_INET, type, 0)};
     21 	if (!incoming)
     22 		err(1, "socket");
     23 
     24 	if (::setsockopt(incoming, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof reuseaddr))
     25 		err(1, "setsockopt");
     26 	if (::bind(incoming, (sockaddr const*)&addr, sizeof addr))
     27 		err(1, "bind");
     28 	if (::listen(incoming, 10))
     29 		err(1, "listen");
     30 
     31 	return incoming;
     32 }
     33 
     34 descriptor accept(descriptor& incoming)
     35 {
     36 	struct sockaddr_in addr;
     37 	socklen_t addr_size = sizeof addr;
     38 	descriptor conn{::accept(incoming, (sockaddr*)&addr, &addr_size)};
     39 
     40 	if (!conn)
     41 		err(1, "accept");
     42 
     43 	std::cout << "Connection " << conn << " from " << inet_ntoa(addr.sin_addr) << std::endl;
     44 	return conn;
     45 }
     46 
     47 }