Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#define MAX 100
#define IPSIZE 20
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in *) sa)->sin_addr);
}
return &(((struct sockaddr_in6 *) sa)->sin6_addr);
}
char buff[100];
char buf[100];
char *cont;
int main()
{
int sockfd, new_fd, numbytes;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr;
int yes = 1, len = 16, i = 0;
char names[20];
char line[75];
char opr[2];
char s[INET6_ADDRSTRLEN];
char **lines_array;
int rv, line_counter = 0;;
FILE *fp;
struct sockaddr *name;
socklen_t size;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
fp = fopen("ipadd.ini", "r");
while (fgets(line, sizeof(line), fp) != NULL) {
line_counter++;
}
lines_array = (char **) malloc((line_counter) * IPSIZE);
if (fp == NULL) {
printf("cannot open file");
return 1;
} else {
rewind(fp);
while (fgets(line, sizeof(line), fp) != NULL) {
lines_array[i++] = strdup(line);
}
}
printf("Line counter %d", line_counter);
/* for (i = 0; i <line_counter; i++)
{
printf("\n%s", lines_array[i]);
}
free(lines_array); */
int su = 0;
while (su == 0) {
i = 0;
while (i < line_counter) {
if ((rv =
getaddrinfo(lines_array[i], "3456", &hints,
&servinfo)) == -1) {
fprintf(stderr, "getaddrinfo:%s", gai_strerror(rv));
continue;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd =
socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("\n client:socket");
continue;
}
printf(" socket %d\n", sockfd);
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("\nclient:connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client:failed");
continue;
}
strcpy(names, lines_array[i++]);
inet_ntop(p->ai_family,
get_in_addr((struct sockaddr *) p->ai_addr), s,
sizeof s);
int count = 2;
if (recv(sockfd, buf, sizeof buf, 0) == -1)
perror("ee");
len = 0;
printf("message from server:%s", buf);
if ((send(sockfd, names, sizeof names, 0)) == -1)
perror("err");
if ((recv(sockfd, buf, sizeof buf, 0)) == -1)
perror("p");
printf("\n The no of lines in file is %s", buf);
len = count = atoi(buf);
printf("\ncount %d", count);//till this it works good
//-----------------------------------------------------------------------------
while (count != 0) {
if ((recv(sockfd, buff, sizeof buff, 0)) == -1)
perror("k");
printf("\n%s", buff);// Here is the problem:prints blank
count--; //The server sends the information
//successfully but the client receives it
//correctly sometimes,but not always.
}
//-------------------------------------------------------------------------------------------
if (len > 0)
return 2;
}
i = 0;
}
return 0;
}