Thread: sockets and printf

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    4

    sockets and printf

    Hello, im having a problem with a piece of code. The code implements a Server whici communicates with another application through a socket:

    The code:
    Code:
    #include "stdio.h"
    #include "stdlib.h"
    #include "sys/socket.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "error.h"
    #include "strings.h"
    #include "string.h"
    #include "unistd.h"
    #include "arpa/inet.h"
    #include <glib.h>
    //#include <glib/gprintf.h>
    
    #define ERROR    -1
    #define MAX_CLIENTS    1
    #define MAX_DATA    1024
    
    
    main()
    {
        struct sockaddr_in server;
        struct sockaddr_in client;
        int sock;
        int new;
        int sockaddr_len = sizeof(struct sockaddr_in);
        int data_len;
        char data[MAX_DATA];
        int az,el;
        gchar  azstr[8],elstr[8];
    
    
        close(3);
    
        if((sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
        {
            perror("server socket: ");
            exit(-1);
        }
    
        server.sin_family = AF_INET;
        server.sin_port = htons(atoi("4533"));
        server.sin_addr.s_addr = INADDR_ANY;
        bzero(&server.sin_zero, 8);
    
        if((bind(sock, (struct sockaddr *)&server, sockaddr_len)) == ERROR)
        {
            perror("bind : ");
            exit(-1);
        }
    
        if((listen(sock, MAX_CLIENTS)) == ERROR)
        {
            perror("listen");
            exit(-1);
        }
        printf("\nThe TCPServer Waiting for client on port %d\n",ntohs(server.sin_port));
            fflush(stdout);
    
        while(1) // Better signal handling required
        {
            if((new = accept(sock, (struct sockaddr *)&client, &sockaddr_len)) == ERROR)
            {
                perror("accept");
                exit(-1);
            }
    
            printf("New Client connected from port no %d and IP %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));
    
            data_len = 18;
            az = 1;
            el = 1;
            char* buff;
            while(data_len)
            {
            	g_ascii_formatd (azstr, 8, "%7.2f", az);
            	g_ascii_formatd (elstr, 8, "%7.2f", el);
            	buff = g_strdup_printf ("%s\n%s\n", azstr, elstr);
    
    			data_len = recv(new, data, MAX_DATA, 0);
    
            	//printf("\nRecieved mesg from client: %s", data);
            	if(data_len==2){
            		send(new, buff, 20, 0);
            	}else{
            		send(new, "RPRT 0\n", 7, 0);
            	}
            	//strncpy(data,data,data_len);
            	printf("%d",data_len);
            	if(data_len==2){
            		az++;
    				el++;
            	}
            }
    
            printf("Client disconnected\n");
    
            close(new);
    
        }
    
        close(sock);
    
    
    }
    The problem is in the red zone, the line
    Code:
    printf("%d",data_len);
    prints the "data_len" integer but the second time the line is executed.

    One example:
    suppose data_len == 19, then the printf is executed and nothing appears in the terminal, in a second time data_len==23, printf is executed but this time the two values are printed in the screen:
    19
    23

    Whats going on?

    Hope i was clear, thanks in advance for the help

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    If you want to see data_len on each iteration, then you need to flush the output stream

    Either
    Code:
    printf("%d\n",data_len);
    Or
    Code:
    printf("%d",data_len);
    fflush(stdout);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Posts
    4
    It doesnt work... it still gets executed twice before being printed in the screen

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Can you copy/paste your actual screen log?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Apr 2011
    Posts
    4
    The TCPServer Waiting for client on port 4533
    New Client connected from port no 40190 and IP 127.0.0.1
    2
    18
    2
    18
    2
    18
    2
    18
    2
    18
    2
    18
    2
    18
    2
    18
    2

    the 2 and 18 values are printed at the same time

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    The only real possibility I can think of is what Salem already mentioned. Can we see your modified code? Also, any test data and/or your test client program would be immensely helpful.

  7. #7
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    I think I've lost count of how many times people have confused themselves because they didn't put '\n' at the end of the strings they are printing. Without that, you not only get this flushing problem, but all your output gets jammed onto one line with no breaks in between, that can't possibly be what you want.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  8. #8
    Registered User
    Join Date
    Apr 2011
    Posts
    4
    Here is the modified code:

    Code:
    #include "stdio.h"
    #include "stdlib.h"
    #include "sys/socket.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "error.h"
    #include "strings.h"
    #include "string.h"
    #include "unistd.h"
    #include "arpa/inet.h"
    #include <glib.h>
    //#include <gstring.h>
    
    #define ERROR    -1
    #define MAX_CLIENTS    1
    #define MAX_DATA    1024
    
    
    main()
    {
        struct sockaddr_in server;
        struct sockaddr_in client;
        int sock;
        int new;
        int sockaddr_len = sizeof(struct sockaddr_in);
        int data_len;
        char data[MAX_DATA];
        int az,el;
        gchar  azstr[8],elstr[8];
    
    
        close(3);
    
        if((sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
        {
            perror("server socket: ");
            exit(-1);
        }
    
        server.sin_family = AF_INET;
        server.sin_port = htons(atoi("4533"));
        server.sin_addr.s_addr = INADDR_ANY;
        bzero(&server.sin_zero, 8);
    
        if((bind(sock, (struct sockaddr *)&server, sockaddr_len)) == ERROR)
        {
            perror("bind : ");
            exit(-1);
        }
    
        if((listen(sock, MAX_CLIENTS)) == ERROR)
        {
            perror("listen");
            exit(-1);
        }
        printf("\nThe TCPServer Waiting for client on port %d\n",ntohs(server.sin_port));
            fflush(stdout);
    
        while(1) // Better signal handling required
        {
            if((new = accept(sock, (struct sockaddr *)&client, &sockaddr_len)) == ERROR)
            {
                perror("accept");
                exit(-1);
            }
    
            printf("New Client connected from port no %d and IP %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));
    
            data_len = 18;
            az = 1;
            el = 1;
            char* buff;
            while(data_len)
            {
            	g_ascii_formatd (azstr, 8, "%7.2f", az);
            	g_ascii_formatd (elstr, 8, "%7.2f", el);
            	buff = g_strdup_printf ("%s\n%s\n", azstr, elstr);
    
    			data_len = recv(new, data, MAX_DATA, 0);
    
            	//printf("\nRecieved mesg from client: %s", data);
            	if(data_len==2){
            		send(new, buff, 20, 0);
            	}else{
            		send(new, "RPRT 0\n", 7, 0);
            	}
            	//strncpy(data,data,data_len);
            	printf("%d\n",data_len);
    		fflush(stdout);
            	if(data_len==2){
            		az++;
    				el++;
            	}
            }
    
            printf("Client disconnected\n");
    
            close(new);
    
        }
    
        close(sock);
    
    
    }
    Also the test program is Gpredict, im using it in linux. its the rotator controller.

    Thanks

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I ran your program and sent some simple test data to your program. Here's the output:
    $ ./server &
    The TCPServer Waiting for client on port 4533
    $ echo "foobar" | nc localhost 4533
    New Client connected from port no 47873 and IP 127.0.0.1
    RPRT 0
    7
    RPRT 0
    0
    Client disconnected
    That's pretty much what I expected. No strange repeating behavior. Your server is generally working correctly.

    Some other notes and questions that may or may not be related to your problem:
    • You don't check the return value of send/recv (they return -1). Print a message with perror if either fails.
    • If data_len comes back as 2, you need to send strlen(buff) bytes, not 20.
    • What output do you get if you initialize data_len to something else, like 13?
    • You allocate memory for buff every time through the loop, but never free it.
    • You arbitrarily close file descriptor 3 at the beginning of the program. Why?
    • It's int main(void), and return an int at the end (usually 0).
    • sockaddr_len should be of type socklen_t.
    • Your includes should all be in < >. Quotes are generally for headers you write.

    It might help if you put in lots more diagnostic messages, uncommented some of those printf's, etc. You could try throwing in some sleep() calls too, to see if you can force a delay between the two numbers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sockets tutorial, datagram sockets example not working for me
    By caesius in forum Networking/Device Communication
    Replies: 14
    Last Post: 12-26-2009, 03:40 PM
  2. make printf using printf?
    By germaneater in forum C Programming
    Replies: 9
    Last Post: 11-10-2004, 10:58 PM
  3. Sockets
    By Korhedron in forum Networking/Device Communication
    Replies: 9
    Last Post: 04-24-2004, 09:52 PM
  4. Sockets
    By EvilBaby in forum C Programming
    Replies: 6
    Last Post: 03-30-2004, 05:57 PM
  5. Sockets
    By billholm in forum C++ Programming
    Replies: 5
    Last Post: 05-17-2002, 03:36 AM