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