Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <iostream>
- #include <netdb.h> // use getprotobyname
- #include <arpa/inet.h> // use inet_pton
- #include <cerrno> // for errorno
- #include <cstring> // for errorstring
- #include <netinet/in.h>
- // how many connections will wait in queue?
- #define CONNECTION_QUEUE_COUNT 10
- #define SERVER_IP_ADDRESS "127.0.0.1" // bind to localhost
- #define SERVER_PORT 6666 // port to bind to
- /**
- Obtains tcp socket via socket()
- @author Filip Sivák <sivakfil@fel.cvut.cz>
- @throws int 1, if socket fails
- */
- int getTcpSocket() {
- int sock;
- sock = socket(PF_INET, SOCK_STREAM, getprotobyname("tcp")->p_proto);
- if( sock < 0 ) throw 1;
- return sock;
- }
- /**
- Obtains sockaddr_in via inet_pton
- @author: Filip Sivák <sivakfil@fel.cvut.cz>
- */
- struct sockaddr_in getAddress(const char address, int port) {
- struct sockaddr_in ip4;
- ip4.sin_family = AF_INET;
- ip4.sin_port = htons( port ); // hostByteOrder --> networkByteOrder
- ip4.sin_addr.s_addr = inet_addr( &address );
- return ip4;
- }
- /**
- Binds given socket to given address
- You should obtain address by getAddress()
- @throws 2 if error occurs during bind
- @author Filip Sivák<sivakfil@fel.cvut.cz>
- */
- void doBind(int socket, struct sockaddr_in address) {
- int binded = 0;
- binded = bind(socket, (struct sockaddr *)&address, sizeof address);
- if(binded != 0) {
- throw 2;
- }
- }
- /**
- Accepts incoming connections
- @param sockaddr_storage *incoming_addr - pointer to incoming address
- that will be set
- @throw error no. 3 on error
- @returns socket file descriptor of incoming connection
- */
- int doAccept(int socket, struct sockaddr_storage *incoming_addr) {
- int accepted;
- socklen_t addrSize;
- addrSize = sizeof incoming_addr;
- accepted = accept(socket, (struct sockaddr *) incoming_addr, &addrSize);
- if(accepted == -1) {
- throw 3;
- }else {
- return accepted;
- }
- }
- int main(void) {
- try {
- int socket = getTcpSocket();
- std::cout << "Yo! I have a socket for you: " << socket << "\n";
- struct sockaddr_in socketAddress;
- const char *addr = SERVER_IP_ADDRESS;
- socketAddress = getAddress(*addr, SERVER_PORT);
- doBind( socket, socketAddress );
- std::cout << "Yo! I have binded your socket esse!\n";
- int listenError = listen( socket, CONNECTION_QUEUE_COUNT );
- if(listenError == -1) throw 4;
- std::cout << "Yo Homie! I'm listening. Taalk to me! \n";
- struct sockaddr_storage incoming_addr;
- int socketIncoming = doAccept(socket, &incoming_addr);
- std::cout << "Hi Hi Hi mr.: " << socketIncoming << "! \n";
- }catch(int errorNo) {
- std::cout << "-----------------------\n";
- std::cout << "Error with no: " << errorNo << " occured!\n";
- std::cout << "Error: " << std::strerror(errno) << " \n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement