[Linuxtrent] Re: OT: Socket [Programmazione]

  • From: Nivox <zito.andrea@xxxxxxxxxx>
  • To: linuxtrent@xxxxxxxxxxxxx
  • Date: Wed, 7 Apr 2004 22:08:13 +0200

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Alle Wednesday 07 April 2004 21:54, Luca Manganelli ha scritto:
> Potresti postare il tuo codice...
Richiesta più che legittima :-D

Allego i sorgenti della classe Socket visto che quelli del programma di test
non fanno praticamente nulla...
Vi prego solo di non essere troppo duri riguardo la sua qualità :-).
In ogni caso ogni commento a riguardo è gradito.

Ciao e grazie
- -- 
Nivox

Linux Registered User #290686
Powered by: Debian Testing/Unstable
JABBER: nivox@xxxxxxxxxxxxxxx
GPG Key ID: 0xC6A50D8D (info: www.gnupg.org)
GPG Keyserver: http://www.keyserver.net
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAdF+tfhOftsalDY0RAiZ2AKCvNRcEnqUdd5lEzlccEmpCms0TVgCbBkD/
iD/YsLldFazcOGcKiC26vaU=
=OcUi
-----END PGP SIGNATURE-----
/***************************************************************************
 *   Copyright (C) 2004 by Andrea Zito                                     *
 *   nivox@xxxxxxxxxxxxxxxxxxxx                                            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#ifndef ASOCK_H
#define ASOCK_H


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <string>

#include <errno.h>
#include <fcntl.h>

const int MAXRECV = 500;

#define CREATE_ERROR       10000001
#define BIND_ERROR         10000002
#define LISTEN_ERROR       10000003
#define ACCEPT_ERROR       10000004
#define CONNECTION_ERROR   10000005
#define CONVERSION_ERROR   10000006
#define SEND_ERROR         10000007
#define RECEIVE_ERROR      10000008
#define MODIFYSOCKET_ERROR 10000009


/**************************************************************
/***Structure: Socket_Error
/***Version: 0.1
/***Job: Identifica e descrive un errere generato da una 
/***     funzione della classe aSock
/**************************************************************/
struct Socket_Error{
  int error;
  std::string description;
  Socket_Error(int error_code,std::string error_description) 
{error=error_code;description = error_description;}
};


/**************************************************************
/***Structure: NonValid_Error
/***Version: 0.1
/***Job: Segnala che il socket descriptor non è valido
/**************************************************************/
struct NonValidSocket{};


/**************************************************************
/***Class: aSock (Arys Socket Class)
/***Version: 0.5
/***Job: Fornisce le funzioni di base per creare una struttura
/***     client server tramite l'utilizzo delle soket.
/***     Se vengono riscontrati degli errori la classe solleva
/***     un eccezione contenente la descrizione
/**************************************************************/

class aSock{
  int sock_fd;
  sockaddr_in sock_addr;

public:
  aSock();
  ~aSock();

   //Server Functions
  void create();
  void bind(const int port);
  void listen() const;
  int accept() const;

  //Client Functions
  void connect(const std::string host, const int port);
  void operator = (const int i) {sock_fd = i;};

  //Data Trasmission Functions
  void send(const std::string msg) const;
  std::string receive() const;
  void operator << (const std::string msg){send(msg);};
  void operator >> (std::string &msg) {msg = receive();};
 
  //Utils Functions
  void set_non_blocking(const bool value);
  bool is_valid() const {return sock_fd != -1;}
};

#endif 
/***************************************************************************
 *   Copyright (C) 2004 by Andrea Zito                                     *
 *   nivox@xxxxxxxxxxxxxxxxxxxx                                            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/


#include "asock.h" 


/*************************************************
/* aSock() - modified 10/2/2004
/* ----------------------------
/* Inizializza le variabili
/************************************************/
aSock::aSock(){
  //Set the socket descriptor to Non Created value
  sock_fd = -1;

  //Clean the sock_addr struct
  memset(&sock_addr, 0, sizeof(sock_addr));
}


/*************************************************
/* ~aSock() - modified 10/2/2004
/* ----------------------------
/* Dsctuggeil socket se questo è attivo
/************************************************/
aSock::~aSock(){
  //If the socket is active then close it
  if (is_valid()) ::close(sock_fd);
}



/*************************************************
/* create() - modified 10/2/2004
/* ----------------------------
/* Crea il socket. 
/* Eccezioni:
/*   - NonValidSocket()
/*   - Socket_Error(int error,std::string description)
/************************************************/
void aSock::create(){
  //Create the socket
  if( (sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    throw Socket_Error(CREATE_ERROR,strerror(errno));

  //Check if it valid
  if (!is_valid())
    throw NonValidSocket();
}



/*************************************************
/* bind() - modified 10/2/2004
/* ----------------------------
/* Inizializza il socket e prende il controllo della
/* porta specificata.
/* Eccezioni: 
/*   - NonValidSocket()
/*   - Socket_Error(int error,std::string description)
/************************************************/
void aSock::bind(const int port){
  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();

  sock_addr.sin_family = AF_INET;
  sock_addr.sin_addr.s_addr = INADDR_ANY;
  sock_addr.sin_port = htons(port);

  if ( ::bind (sock_fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0 )
    throw Socket_Error(BIND_ERROR,strerror(errno));
}


/*************************************************
/* listen() - modified 10/2/2004
/* ----------------------------
/* Imposta il socket in ascolto.
/* Eccezioni:
/*  - NonValidSocket()
/*  - Socket_Error(int error,std::string description)
/************************************************/
void aSock::listen() const{
  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();

  if ( ::listen(sock_fd, SOMAXCONN) < 0 )
    throw Socket_Error(LISTEN_ERROR,strerror(errno));
}


/*************************************************
/* accept() - modified 10/2/2004
/* ----------------------------
/* Accetta le connessioni.
/* Eccezioni:
/*  - NonValidSocket()
/*  - Socket_Error(int error,std::string description)
/************************************************/
int aSock::accept() const{
  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();

  int addr_len = sizeof(sock_addr);
  int new_sock;
  if ( ( new_sock = ::accept(sock_fd, (sockaddr *) &sock_addr, (socklen_t *) 
&addr_len) ) <= 0 )
    throw Socket_Error(ACCEPT_ERROR,strerror(errno));

  return new_sock;
}


/*************************************************
/* connect() - modified 10/2/2004
/* ----------------------------
/* Effettua la connessione ad un host remoto.
/* Eccezioni:
/*  - NonValidSocket()
/*  - Socket_Error(int error,std::string description)
/************************************************/
void aSock::connect(const std::string host, const int port){
  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();
  
  sock_addr.sin_family = AF_INET;
  sock_addr.sin_port = htons(port);

  if ( inet_pton(AF_INET, host.c_str(), &sock_addr.sin_addr) <= 0 )
    throw Socket_Error(CONVERSION_ERROR,strerror(errno));

  if ( ::connect(sock_fd, (sockaddr *) &sock_addr, sizeof(sock_addr)) < 0 )
    throw Socket_Error(CONNECTION_ERROR,strerror(errno));
}


/*************************************************
/* send() - modified 10/2/2004
/* ----------------------------
/* Spedisce dati ad un host remoto
/* Eccezioni:
/*  - NonValidSocket()
/*  - Socket_Error(int error,std::string description)
/************************************************/
void aSock::send(const std::string msg) const{
  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();
  
  if ( ::send(sock_fd, msg.c_str(), msg.size(), MSG_NOSIGNAL) < 0)
    throw Socket_Error(SEND_ERROR,strerror(errno));
}


/*************************************************
/* receive() - modified 10/2/2004
/* ----------------------------
/* Riceve dati dall' host remoto.
/* Eccezioni:
/*  - NonValidSocket()
/*  - Socket_Error(int error,std::string description)
/************************************************/
std::string aSock::receive() const{
  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();

  char buf[MAXRECV + 1];
  memset(buf,0,(MAXRECV + 1));
  
  if ( ::recv(sock_fd, buf, MAXRECV,0) < 0)
    throw Socket_Error(RECEIVE_ERROR,strerror(errno));
  return buf;
}

/*************************************************
/* set_non_blocking() - modified 10/2/2004
/* ----------------------------
/* Imposta il socket in modalita bloccante o 
/* viceversa.
/*  - NonValidSocket()
/*  - Socket_Error(int error,std::string description)
/************************************************/
void aSock::set_non_blocking(const bool value){
  int flags;

  //Check if the socket descriptor is valid
  if (!is_valid())
    throw NonValidSocket();

  if ( ( flags = fcntl(sock_fd, F_GETFL) ) < 0 )
    throw Socket_Error(MODIFYSOCKET_ERROR,strerror(errno));

  if (value)
    flags = (flags | O_NONBLOCK);
  else
    flags = (flags | ~O_NONBLOCK);

  if ( fcntl(sock_fd, F_SETFL, flags) < 0)
    throw Socket_Error(MODIFYSOCKET_ERROR,strerror(errno));
}

Other related posts: