LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 01-02-2009, 03:15 PM   #1
brevleq
Member
 
Registered: Sep 2004
Location: Brazil
Distribution: Slackware
Posts: 45

Rep: Reputation: 15
Unhappy Socket C++


Hey guys!

I'm trying implement a small server for a university work, my server is creating, binding and listening but it don't accept any connection, these are the files I'm using in server:

Code:
// Definition of the Socket class

#ifndef SOCKET_H
#define SOCKET_H


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


const int MAXHOSTNAME = 200;
const int MAXCONNECTIONS = 5;
const int MAXRECV = 500;

class Socket
{
 public:
  Socket();
  virtual ~Socket();

  // Server initialization
  bool create();
  bool bind ( const int port );
  bool listen() const;
  int accept () const;

  // Client initialization
  bool connect ( const std::string host, const int port );

  // Data Transimission
  bool send ( const std::string ) const;
  int recv ( std::string& ) const;


  void set_non_blocking ( const bool );

  bool is_valid() const { return m_sock != -1; }

 private:

  int m_sock;
  sockaddr_in m_addr;
};


#endif
Code:
// Implementation of the Socket class.


#include "Socket.h"
#include "string.h"
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>



Socket::Socket() :  m_sock ( -1 ){
  memset ( &m_addr,0,sizeof ( m_addr ) );
}

Socket::~Socket(){
  if ( is_valid() )
    ::close ( m_sock );
}

bool Socket::create(){
  m_sock = socket (AF_INET,SOCK_STREAM,0);  //cria o socket
  if ( ! is_valid() )
    return false;
  // TIME_WAIT - argh
  int on = 1;
  if (setsockopt(m_sock,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on))==-1)  //define as opções do socket
    return false;
  return true;
}



bool Socket::bind (const int port){
  if(!is_valid()){
      return false;
    }
  m_addr.sin_family = AF_INET;			//define as opções no struct
  m_addr.sin_addr.s_addr = INADDR_ANY;
  m_addr.sin_port = htons(port);
  int bind_return = ::bind (m_sock,(struct sockaddr *)&m_addr,sizeof(m_addr));
  if ( bind_return == -1 ){
      return false;
    }
  return true;
}


bool Socket::listen() const{
  if ( ! is_valid() ){
      return false;
    }
  int listen_return = ::listen ( m_sock, MAXCONNECTIONS );
  if ( listen_return == -1 ){
      return false;
    }
  return true;
}


int Socket::accept (void) const{
  int addr_length = sizeof ( m_addr );
  int new_socket = ::accept ( m_sock, ( sockaddr * ) &m_addr, ( socklen_t * ) &addr_length );
  if ( new_socket <= 0 )
    return(-1);
  else
    return(new_socket);
}


bool Socket::send ( const std::string s ) const{
  int status = ::send ( m_sock, s.c_str(), s.size(), MSG_NOSIGNAL );
  if ( status == -1 ){
      return false;
    }
  else{
      return true;
    }
}


int Socket::recv ( std::string& s ) const{
  char buf [ MAXRECV + 1 ];
  s = "";
  memset ( buf, 0, MAXRECV + 1 );
  int status = ::recv ( m_sock, buf, MAXRECV, 0 );
  if ( status == -1 ){
      std::cout << "status == -1   errno == " << errno << "  in Socket::recv\n";
      return 0;
    }
  else if ( status == 0 ){
      return 0;
    }
  else{
      s = buf;
      return status;
    }
}



bool Socket::connect ( const std::string host, const int port ){
  if ( ! is_valid() ) return false;
  m_addr.sin_family = AF_INET;
  m_addr.sin_port = htons ( port );
  int status = inet_pton ( AF_INET, host.c_str(), &m_addr.sin_addr );
  if ( errno == EAFNOSUPPORT ) return false;
  status = ::connect ( m_sock, ( sockaddr * ) &m_addr, sizeof ( m_addr ) );
  if ( status == 0 )
    return true;
  else
    return false;
}

void Socket::set_non_blocking ( const bool b ){
  int opts;
  opts = fcntl ( m_sock,F_GETFL );
  if ( opts < 0 ){
      return;
    }
  if ( b )
    opts = ( opts | O_NONBLOCK );
  else
    opts = ( opts & ~O_NONBLOCK );
  fcntl ( m_sock,
	  F_SETFL,opts );
}
Code:
#ifndef MAINSOCKET_H
#define MAINSOCKET_H

#include "Thread.h"
#include "SocketManipulator.h"
#include "Socket.h"

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

class MainSocket : public Thread,public Socket{
public:
    MainSocket(int p);
    void setMaxClients(int q);

protected:
/*    int sock;
    sockaddr_in address;*/
    QList<SocketManipulator *> manipulators;
    int maxClients;
    int port;

/*    void create(void);
    void bind(const int p);
    void listen(void);
    void accept(void);*/
    void startThread(void);
};

#endif // MAINSOCKET_H
Code:
#include "MainSocket.h"

#include <iostream>

using namespace std;

MainSocket::MainSocket(int p){

    cout<<"CONSTUTOR MAINSOCKET\n";

    port=p;
    maxClients=5;
    while(!create())
        cout<<"tentando criar socket\n";
    while(!bind(port))
        cout<<"bind\n";
    while(!listen())
        cout<<"listen\n";
    set_non_blocking(true);
    alocThread();
}

void MainSocket::setMaxClients(int q){
    maxClients=q;
}

void MainSocket::startThread(void){

    cout<<"porra!!!\n";

    int s;
    while(true){
        s=accept();
        cout<<s<<"thread";
        //while(s=accept()==-1)
            cout<<"accept\n";
/*        SocketManipulator *newSock=NULL;
        if(newSock==NULL)
            newSock=new SocketManipulator(accept());*/
    }
}
Code:
#ifndef SOCKETMANIPULATOR_H
#define SOCKETMANIPULATOR_H

#include <QList>
#include <QStringList>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <arpa/inet.h>

#include "Thread.h"
#include "PipeReader.h"
#include "PipeWriter.h"

class SocketManipulator:public Thread{
public:
    static const int DIGITAL=0;
    static const int ANALOGIC=1;

    SocketManipulator(int s);

protected:
    int sock;
    static const int BUFFER = 45;
    PipeReader *pipeReader;
    PipeWriter *pipeWriter;
    QList<int> signedDIn;
    QList<int> signedAIn;

    void send(QString msg);
    QString dInMsg();
    QString dOutMsg();
    QString aInMsg();
    QString aOutMsg();
    QString aTypesMsg();
    void receive(void);
    void sign(int i,int t);
    void unsign(int i,int t);
    void startThread(void);
};

#endif // SOCKETMANIPULATOR_H
Code:
#include "SocketManipulator.h"

#include <iostream>

using namespace std;

SocketManipulator::SocketManipulator(int s){
    sock=s;

    cout<<sock<<"\n";

    pipeReader=PipeReader::getInstance();
    pipeWriter=PipeWriter::getInstance();

    alocThread();
}

void SocketManipulator::send(QString msg){
    if(::send(sock, msg.toStdString().c_str(),msg.size(), MSG_NOSIGNAL )==-1)
        return;
}

QString SocketManipulator::dInMsg(){
    QString msg;
    QStringList lista;
    msg=pipeReader->getDIn();
    lista=msg.split(":");
    lista=lista.value(1).split(";");
    msg.clear();
    msg="aIn:";
    for(int cont=0;cont<signedDIn.size();cont++){
        msg+=lista.value(signedDIn.value(cont));
        if(cont<signedDIn.size()-1)
            msg+=";";
    }
    return(msg);
}

QString SocketManipulator::dOutMsg(){
    return(pipeReader->getDOut());
}

QString SocketManipulator::aInMsg(){
    QString msg;
    QStringList lista;
    msg=pipeReader->getAIn();
    lista=msg.split(":");
    lista=lista.value(1).split(";");
    msg.clear();
    msg="aIn:";
    for(int cont=0;cont<signedAIn.size();cont++){
        msg+=lista.value(signedAIn.value(cont));
        if(cont<signedAIn.size()-1)
            msg+=";";
    }
    return(msg);
}

QString SocketManipulator::aOutMsg(){
    return(pipeReader->getAOut());
}

QString SocketManipulator::aTypesMsg(){
    QString msg;
    QStringList lista;
    msg=pipeReader->getATypes();
    lista=msg.split(":");
    lista=lista.value(1).split(";");
    msg.clear();
    msg="aIn:";
    for(int cont=0;cont<signedAIn.size();cont++){
        msg+=lista.value(signedAIn.value(cont));
        if(cont<signedAIn.size()-1)
            msg+=";";
    }
    return(msg);
}

void SocketManipulator::receive(void){
    char buf[BUFFER];
    QString msg;
    QStringList lista;
    memset(buf, 0, BUFFER);
    if(::recv(sock, buf, BUFFER, 0)==-1)
        return;
    msg=buf;
    lista=msg.split(":");
    if(lista.value(0)=="sign"){
        lista=lista.value(1).split(";");
        sign(lista.value(0).toInt(),lista.value(1).toInt());
    }
    else
        pipeWriter->requestWrite(msg);

}

void SocketManipulator::sign(int i,int t){
    switch(t){
        case DIGITAL  :  signedDIn.append(i);
                         qSort(signedDIn.begin(),signedDIn.end());
                         break;
        case ANALOGIC :  signedAIn.append(i);
                         qSort(signedAIn.begin(),signedAIn.end());
                         break;
    }
}

void SocketManipulator::unsign(int i,int t){
    switch(t){
        case DIGITAL  :  signedDIn.removeAll(i);
                         break;
        case ANALOGIC :  signedAIn.removeAll(i);
                         break;
    }
}

void SocketManipulator::startThread(void){
    while(true){
        send("olá\n");
        /*send(dInMsg());
        send(dOutMsg());
        send(aInMsg());
        send(aTypesMsg());
        send(aOutMsg());
        receive();*/
    }
}
I've made a client just for test it, but no ones run well, the server is always returning -1 when accept is called!!

What should I do to send and receive messages in this server??
 
Old 01-02-2009, 04:39 PM   #2
wje_lq
Member
 
Registered: Sep 2007
Location: Mariposa
Distribution: FreeBSD,Debian wheezy
Posts: 811

Rep: Reputation: 179Reputation: 179
Two questions:
  1. What is the value of m_sock just before the ::accept() call? I don't mean, what do you think it is? I mean, if you display that value just before calling ::accept(), what do you see?
  2. When ::accept() returns -1, what is the value of errno?
 
Old 01-02-2009, 08:34 PM   #3
itz2000
Member
 
Registered: Jul 2005
Distribution: Fedora fc4, fc7, Mandrake 10.1, mandriva06, suse 9.1, Slackware 10.2, 11.0, 12.0,1,2 (Current)]
Posts: 732

Rep: Reputation: 30
didn't read the code, but, are you sure you can be routed from outside (iptables, NAT, etc?)
check this with nc(server nc -lnvvp <port goes here> and client nc <ip-here> <port here>)



Good luck
 
Old 01-03-2009, 03:39 PM   #4
brevleq
Member
 
Registered: Sep 2004
Location: Brazil
Distribution: Slackware
Posts: 45

Original Poster
Rep: Reputation: 15
I've rewrited the code and ist's running right now!!

Thanks for attention!
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Can't connect to UNIX socket /var/run/clamav/clamd.socket ganick Linux - Server 8 08-01-2008 01:22 PM
AF_LOCAL domain socket versus AF_INET socket performance zzaappp Linux - General 0 06-19-2008 07:50 AM
fseek on a socket descriptor to discard socket buffer? Thinking Programming 1 12-06-2005 09:15 PM
cannot read data at server socket, though client socket sends it jacques83 Linux - Networking 0 11-15-2005 01:58 PM
Unable to connect to UNIX socket /tmp/.esd/socket error while using grip dr_zayus69 Linux - Software 4 08-23-2005 07:28 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:01 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration