LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   C client socket program in Linux (segmentation fault) (https://www.linuxquestions.org/questions/linux-newbie-8/c-client-socket-program-in-linux-segmentation-fault-4175482433/)

why_so_serious 10-28-2013 01:58 AM

C client socket program in Linux (segmentation fault)
 
Hi everyone, I wrote c client program in Linux. I got segmentation fault when I run that program. my program is
Code:

#include <sys/socket.h>
#include <sys/types/h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <uniistd.h>
#include <errno.h>
#include <arpa/net.h>

int main (void)
{
        int sockfd, n;
        struct sockaddr_in serv_addr;
        struct hostent *server;
       
        char buffer[256];
        char hostname[1024];
        gethostname(hostname, sizeof(hostname));
        serverINFO = gethostbyname(hostname);
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            printf("ERROR opening socket");
            return 1;
        }
        if(serverINFO == NULL)
        {
                printf("Problem interpreting host\n");
                return 1;
        }
        serv_addr.sin_family = serverINFO ->h_addrtype;
        memcpy((char *) &serv_addr.sin_addr, serverINFO ->h_addr_list[0], serverINFO->h_length);
       
        serv_addr.sin_port = htons (SERVERPORT);
        if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof (serv_addr)) < 0)
        {
            printf("ERROR connecting");
            return 1;
        }
        printf("Please enter the message: ");
        bzero(buffer, 256);
        fgets(buffer,255,stdin);
        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("here we are %s\n", buffer);
        close(sockfd);
}


pan64 10-28-2013 03:08 AM

how is it related to that post? http://www.linuxquestions.org/questi...am-4175482072/
Have you tried debugging?
Have you got warnings during compilation or build?

why_so_serious 10-28-2013 03:23 AM

Quote:

Originally Posted by pan64 (Post 5053512)
how is it related to that post? http://www.linuxquestions.org/questi...am-4175482072/
Have you tried debugging?
Have you got warnings during compilation or build?

Hi, thanks for your ans. I had debugged and solved the problem. Thanks a lot


All times are GMT -5. The time now is 04:27 PM.