hi everyone
well I'm learning network programming currently , I've written a day time client and server but when I run the client it gives me a connection error . Here is my client code

#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<netinet/in.h>
#include<netdb.h>

int main(int argc ,char *argv[])
{
int sockfd, n;
char rcvline[4097];
struct sockaddr_in servadd;
int port;
    if (argc != 3 )
    {
        printf("Error .Usage daytimecli <port> <IPAddr>");
        exit(1);
    }
    if ((sockfd=socket(AF_INET,SOCK_STREAM,0)) <0)
    {
        printf("Socket error \n");
        exit(1);
    }
    port=atoi(argv[1]);
    bzero(&servadd,sizeof(servadd));
    servadd.sin_family=AF_INET;
    servadd.sin_port=htons(port);

    if(inet_pton(AF_INET,argv[2],&servadd.sin_addr) <=0)
    {
        printf("inet_pton error for %s \n",argv[2]);
        exit(1);
    }
    if(connect(sockfd,(struct sockaddr*)&servadd ,sizeof(servadd)) < 0)
    {
        printf("Connect error.\n");
        exit(1);
    }
    while( ( n=read(sockfd,rcvline,4096)) >0)
    {
        rcvline[n]=0;
        if(fputs(rcvline,stdout)==EOF)
        {
            printf("fputs error . \n");
            exit(1);
        }

    }
    if(n<0){
    printf("read error \n");
    exit(1);
    }
exit(0);
}

can you help me to figure the problem ??

Recommended Answers

All 2 Replies

I don't see where you are setting the host ip address in your servadd structure. You are only setting the port. Example:

struct hostent* hostent = gethostbyname(pHost);
.
.
.
servadd.sin_addr = *((struct in_addr*)hostent->h_addr);

I did that in line 28

  if(inet_pton(AF_INET,argv[2],&servadd.sin_addr) <=0)
    {
        printf("inet_pton error for %s \n",argv[2]);
        exit(1);
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.