clinuxsockets

C socket program error


This is my C client code. Somehow it is not working. It worked when I tried with argument passing.
I want the program to ask user to give hostname then it will ask for portname and then the message to send:

Enter hostname: localhost
Enter portname: 56456
Enter message : Hi user
Enter message : What's up
Enter message : How are you

And once the host and port given it should not ask for again (until restart the program). I tried with do while loop, but it is not working. On server it will display the sent message

Here is my code:

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

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

//int main(int argc, char *argv[])
int main()
{
    char *argv[256];
    int argc;
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    printf("\n\nEnter Hostname\n\n");
    fgets(argv[0],256,stdin);
    char buffer[256];
    if (argc < 3) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
        error("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
        error("ERROR connecting");


    printf("Please enter the message: ");
    bzero(buffer,256);
    //buffer = tempFunc();
    fgets(buffer,255,stdin);
    printf("\n\nHere Goes the output\n%s",buffer);
    n = write(sockfd,buffer,strlen(buffer));
    if (n < 0) 
         error("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0) 
         error("ERROR reading from socket");
    printf("%s\n",buffer);
    close(sockfd);
    return 0;

}

Solution

  • First, do not use char * argv[256]

    char buffer[256];
    printf("\n\nEnter Hostname\n\n");
    fgets(buffer,256,stdin);
    

    Then check Removing trailing newline character from fgets() input to deal with fgets.

    For an infinite loop, don't do

    int a=2; // Useless declaration
    do
    {
        // Your code
    }while(a=2) // I guess you wanted (a == 2)
    

    use:

    while(1)
    {
        // Your code
    }
    

    Or

    for(;;)
    {
        // Your code
    }
    

    It seems that you need a little bit of training, try some tutorials, look for good practices in C, enable warning flags on compilation and learn to use a debugger like gdb.