Saturday, August 18, 2012

TCP Daytime client Program using C in linux

This is the client program to get the time and date. Daytime server is the server program which is provided by the linux, and it has a specific name in the system i.e. "daytime".


daytimecli.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>

int main(int argc,char *argv[])
{
    int sockfd,len,ret;
    struct sockaddr_in saddr;
    char *hname,buff[256];
    struct hostent *hostinfo;
    struct servent *servinfo;
    if(argc == 1)
        hname = "localhost";
    else
        hname = argv[1];
   
    hostinfo = gethostbyname(hname);
    if(!hostinfo) {
        fprintf(stderr,"No host: %s\n ",hname);
        exit(1);
    }
   
    servinfo = getservbyname("daytime","tcp");
    if(!servinfo) {
        fprintf(stderr,"No day time server \n");
        exit(1);
    }
    printf("Day time server Port: %d\n", ntohs(servinfo->s_port));

    // creating tcp socket
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    saddr.sin_family = AF_INET;
    saddr.sin_port = servinfo->s_port;
    saddr.sin_addr = *(struct in_addr *) *(hostinfo->h_addr_list);
    len = sizeof(saddr);
   
    ret = connect(sockfd,(struct sockaddr *)&saddr,len);
    if(ret == -1) {
        perror("connect ");
        exit(1);
    }
   
    ret = read(sockfd,buff,sizeof(buff));
    buff[ret] = '\0';
    printf("Result: %s and %d bytes read\n",buff,ret);
   
    close(sockfd);

return 0;
}



output:
$gcc -o daytimecli daytimecli.c
$./daytimecli
o/p
Day time server Port: 13
connect : Connection refused

You may get output like this, because your daytime server port is not in active state to receive request. To get enable daytime server port on Click Here and follow procedure.

The Output will be as after enable daytime server

$gcc -o daytimecli daytimecli.c
$./daytimecli
o/p
Day time server Port: 13
Result: 17 AUG 2012 17:56:08 IST
 and 26 bytes read

1 comment:

  1. This is pretty neat. What reading material do you recommend for me to learn more network programming in C. Thanks

    ReplyDelete