Aargh Socket()

This is a discussion on Aargh Socket() within the C++ Programming forums, part of the General Programming Boards category; I'm trying to deal with sockets, not getting consistent results at all. I think it's to do with string handling. ...

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    1

    Aargh Socket()

    I'm trying to deal with sockets, not getting consistent results at all. I think it's to do with string handling. I am not sure what kind of string I need to post for it to resolve.

    Client sends data and returns successful. Server returns successful but the response doesn't print for some reason.

    SERVER:
    Code:
    void Server::setup()
    {
    logger.info("Server setup");
        
        int z, b = 1;
     
        struct sockaddr_in server_address;
        memset(&server_address, 0, sizeof server_address);
        server_address.sin_family = AF_INET;
        server_address.sin_port =  htons(conf.port);
        server_address.sin_addr.s_addr = ntohl(INADDR_ANY);
        
    // Create socket
    serversocket = socket(PF_INET,SOCK_STREAM,0);
        if ( serversocket == -1 )
            bail("socket(2)");
        
    // Bind
        z= bind(serversocket, (struct sockaddr *)&server_address, sizeof (server_address));
        if ( z == -1 )
        {
    bail("binding port");
        }
    
    
    // SO_REUSEADDR
        z= setsockopt(serversocket,SOL_SOCKET, SO_REUSEADDR, &b, sizeof b);
        if ( z == -1 ) 
    bail("setsockopt(2)");
        
    // O_NONBLOCK
    //fcntl(serversocket, F_SETFL, O_NONBLOCK);
        
    // LISTEN
        z = listen(serversocket, 10);
        if(z == -1)
            bail("listen(2)");
        
    // POLL
    pollfds = (structpollfd*) malloc(sizeof(structpollfd));
    	if (pollfds == NULL)
        {
    logger.fail("Server out of memory");
        }
        
    pollfds[0].fd = serversocket;
        pollfds[0].events = POLLIN;
    }
    
    
    int Server::update(char *getbuf)
    {
        int ready = poll(pollfds, 1, 100);
        
        if (ready == -1)
        {
    logger.info("Poll failed");
    returnFALSE;
        }
        
        if (pollfds[0].revents & POLLIN)
        {    
            ssize_t z;
            int sSize = 64;
    	char sbuf[sSize];
    
    
    logger.info("Connection available");
            
            struct sockaddr_in client_address;
            memset(&client_address, 0, sizeof client_address);
            socklen_t alen = sizeof(client_address);
            
    // ACCEPT
            clientsocket = accept(serversocket, (struct sockaddr *)&client_address, &alen);
    if(!clientsocket)
                logger.fail("Accept Fail");
    else
    logger.info("Accept succeed");
    
    
    	z = recv (clientsocket, sbuf, sSize, MSG_DONTWAIT);
    
    
    	snprintf(&sbuf[z], sSize-z, "\r\n\0");
    
    
    	snprintf(getbuf, sSize, sbuf);
    
    
    	logger.data("Received: %s",sbuf);       
     
            respond(getbuf);
            
    //closeConnection();
            
            return TRUE;
        }
        
    returnFALSE;
    }
    
    
    void Server::respond(char *response)
    {
    // SEND
    ssize_t z;
    	int sSize = 64;
    	char sbuf[sSize];
    
    
    	snprintf(sbuf, sSize, response);
    	snprintf(&sbuf[z], sSize-z, "\r\n\0");
    
    
        z = send(clientsocket, sbuf, sSize, 0);
        if (z < 0)
    fprintf(stderr,"send failure\n");
        else
    logger.info("Send Succeed");
    }
    CLIENT
    Code:
    
    int main(int argc, char **argv)
    {
        int abort = 0;
        int port;
    	in_addr_t address;
        char *command;
        
        ssize_t z;
        int com_socket;
        struct sockaddr_in server_address;
        struct timeval timeout;
    
    
        int opt;
    	int val = 0;
        
    //Defaults
        address = inet_addr("127.0.0.1");
        port = 4949;
        
    //INCLUDED ARGUMENTS FROM CLI
    	while((opt = getopt(argc, argv, "a:p:c:")) > 0) 
    	{
    		switch(opt)
    		{
                case 'a':
    				address = inet_addr(optarg);
    				break;
                case 'p':
    				port = atoi(optarg);
                    break;
                case 'c':
    				abort = 1;
    				command = (char *)optarg;
    				break;   
                default:
                    fprintf(stderr, "-a IPADDRESS -p PORT -c COMMAND\n",argv[0]);
            }
        }
    // Server
        memset(&server_address, 0, sizeof(server_address));
        server_address.sin_family = AF_INET;
        server_address.sin_port = htons(port);
        server_address.sin_addr.s_addr = address;
    
    
        if (server_address.sin_addr.s_addr == INADDR_NONE)
            fprintf(stderr, "Server address failed\n");
    
    
        if(!abort)
        {
            fprintf(stderr, "No Command given\n");
            fprintf(stderr, "-a IPADDRESS -p PORT -C COMMAND\n");
            exit(0);
        }
        else
        {
        	fprintf(stderr, "Address %s Port %d\n", inet_ntoa(server_address.sin_addr), port);
        }
    
    
    // Create com_socket
        com_socket = socket(PF_INET, SOCK_STREAM, 0);
        if (com_socket == -1)
             fprintf(stderr, "Socket failed\n");
    
    
        /*
        // Client
        struct sockaddr_in client_address;
        memset(&client_address,0,sizeof client_address);
        client_address.sin_family = AF_INET;
        client_address.sin_port = 0;
        client_address.sin_addr.s_addr = ntohl(INADDR_ANY);
    
        if (client_address.sin_addr.s_addr == INADDR_NONE)
            fprintf(stderr, "Client address failed\n");
    
        // Bind
        z= bind(com_socket, (struct sockaddr *)&client_address, sizeof (client_address));
        if ( z == -1 )
            fprintf(stderr,"Binding port\n");
        */
        
        timeout.tv_sec = 2; /* 2 seconds */ 
        timeout.tv_usec = 0; /* + 0 usec */
        
        socklen_t addrlen = sizeof(struct sockaddr_in);
        
    // Connect
    //z = connectWithTimeout(com_socket, (struct sockaddr *) &server_address, len_inet, &timeout);
        z = connect(com_socket, (struct sockaddr *) &server_address, sizeof(server_address));
        if(z == -1)
        {
            if(errno == EINPROGRESS)
            {
                fprintf(stderr, "EINPROGRESS non block start\n");
            }
            
            if(errno == EALREADY)
            {
                fprintf(stderr, "EALREADY non block subsequent request\n");
            }
            
            fprintf(stderr, "Connect failed\n");
        }
        else 
    	printf("Connect Success\n");
    
    
    	int sSize = 64;
    	char sbuf[sSize];
    
    
    	z = snprintf(sbuf, sSize, command);
            snprintf(&sbuf[z], sSize-z, "\r\n\0");
    
    
    // SEND
        z = send(com_socket, sbuf, sSize, 0);
        if (z < 0)
            fprintf(stderr,"send failure\n");
        else
    	printf("Send Succeeded\n");
        
    // READ
        z = recv(com_socket, sbuf, sSize, MSG_DONTWAIT);
        if (z < 0)
            fprintf(stderr,"receive failure\n");
        else
    	printf("Receive Succeeded\n");
        
    	snprintf(&sbuf[z], sSize-z,"\r\n\0");
    
    
    // Output
        printf("Received Response: %s\n", sbuf);
        
        close(com_socket);
        
        exit(1);
    }

  2. #2
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,449
    You could at least start using C++ code and stop using the C library. Ie, get rid of sprintf, printf, fprintf.
    You could also try find a good C++ networking library. It would save you time from writing your own. Don't know if any good one myself, atm, however.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,649
    Code:
    z = recv (clientsocket, sbuf, sSize, MSG_DONTWAIT);
    snprintf(&sbuf[z], sSize-z, "\r\n\0");
    I might suggest that instead of telling recv you'll accept up to sSize bytes, you tell it you'll accept up to sSize - 3 (for "\r\n\0") bytes, so you're guaranteed that snprintf will actually do something useful. Or I'm misunderstanding your intentions.

    There's also no guarantee you'll receive all the data in one recv call. You should continue reading and appending to your buffer until the recv call returns 0.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. socket
    By iamnew in forum Networking/Device Communication
    Replies: 1
    Last Post: 06-13-2010, 09:12 PM
  2. Socket programming in C with socket.h
    By funzy in forum Networking/Device Communication
    Replies: 13
    Last Post: 08-29-2008, 04:12 AM
  3. Aargh... evil static
    By anon in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 01-12-2008, 11:38 AM
  4. n00b doing a Socket operation on non-socket
    By Kinasz in forum Networking/Device Communication
    Replies: 2
    Last Post: 03-25-2004, 02:29 AM
  5. Aargh mailslots and the like!!
    By Frietbakker in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2004, 10:40 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21