Thread: Linux Sockets in C

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    16

    Linux Sockets in C

    Hi everyone,

    I am trying to learn how to do socket programming. What I am trying to do right now is the following:

    1. Client and Server which communicate on localhost using whichever port I designate
    2. Server has a text file stored on it
    3. Client can send a query to the Server to peruse the text file and get contents (for example if the text file is an address book, I want to be able to send the name of the person as a query and get the Server to return the address after browsing the text file).

    I am trying to do this in Linux because it seems to be the most simple out of all the operating systems in terms of complexity etc.

    If anyone could give me any pointers or a step in the right direction that would be GREAT!

    Thanks!!!!

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    16
    Yeah I found those two tutorials, I kind of understand how to communicate between client and server but I was more wondering in terms of how to peruse the text file as well :S

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Scythed View Post
    Yeah I found those two tutorials, I kind of understand how to communicate between client and server but I was more wondering in terms of how to peruse the text file as well :S
    It's just data transfer from server to client (and back)... sendto() and recvfrom().

    Your server has to store, read and transfer the file contents.
    You client has to receive the contents, store them in memory and display them.

  5. #5
    Registered User
    Join Date
    Nov 2010
    Posts
    16
    Hmmm.... I know generally speaking its very bad form etc to ask for help in the form of code but I am quite new to this and I am trying to figure out how to put it into code..

    I have the following code that I managed to build together for a client and a server, just trying to figure out how to now adapt it to what I need



    Server code

    Code:
    
    
    #include <stdio.h> 
        #include <stdlib.h> 
        #include <errno.h> 
        #include <string.h> 
        #include <sys/types.h> 
        #include <netinet/in.h> 
        #include <sys/socket.h> 
        #include <sys/wait.h> 
    
        #define MYPORT 54321    /* the port users will be connecting to */
    
    
        #define BACKLOG 10     /* how many pending connections queue will hold */
    
        main()
        {
            int sockfd, new_fd;  /* listen on sock_fd, new connection on new_fd */
            struct sockaddr_in my_addr;    /* my address information */
            struct sockaddr_in their_addr; /* connector's address information */
            int sin_size;
    
    	/* generate the socket */
            if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
                perror("socket");
                exit(1);
            }
    
    	/* generate the end point */
            my_addr.sin_family = AF_INET;         /* host byte order */
            my_addr.sin_port = htons(MYPORT);     /* short, network byte order */
            my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
            /* bzero(&(my_addr.sin_zero), 8);   ZJL*/     /* zero the rest of the struct */
    
    	/* bind the socket to the end point */
            if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \
                                                                          == -1) {
                perror("bind");
                exit(1);
            }
    
    	/* start listnening */
            if (listen(sockfd, BACKLOG) == -1) {
                perror("listen");
                exit(1);
            }
    
    		 printf("server starts listnening ...\n");
    
    	/* repeat: accept, send, close the connection */
    	/* for every accepted connection, use a sepetate process or thread to serve it */
            while(1) {  /* main accept() loop */
                sin_size = sizeof(struct sockaddr_in);
                if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
                                                              &sin_size)) == -1) {
                    perror("accept");
                    continue;
                }
                printf("server: got connection from %s\n", \
                                                   inet_ntoa(their_addr.sin_addr));
                if (!fork()) { /* this is the child process */
                    if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
                        perror("send");
                    close(new_fd);
                    exit(0);
                }
                close(new_fd);  /* parent doesn't need this */
    
                while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */
            }
        }

    CLient Code

    Code:
        #include <stdio.h> 
        #include <stdlib.h> 
        #include <errno.h> 
        #include <string.h> 
        #include <netdb.h> 
        #include <sys/types.h> 
        #include <netinet/in.h> 
        #include <sys/socket.h> 
    
        #define PORT 54321    /* the port client will be connecting to */
    
        #define MAXDATASIZE 100 /* max number of bytes we can get at once */
    
        int main(int argc, char *argv[])
        {
            int sockfd, numbytes;  
            char buf[MAXDATASIZE];
            struct hostent *he;
            struct sockaddr_in their_addr; /* connector's address information */
    
            if (argc != 2) {
                fprintf(stderr,"usage: client hostname\n");
                exit(1);
            }
    
            if ((he=gethostbyname(argv[1])) == NULL) {  /* get the host info */
                herror("gethostbyname");
                exit(1);
            }
    
            if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
                perror("socket");
                exit(1);
            }
    
            their_addr.sin_family = AF_INET;      /* host byte order */
            their_addr.sin_port = htons(PORT);    /* short, network byte order */
            their_addr.sin_addr = *((struct in_addr *)he->h_addr);
            bzero(&(their_addr.sin_zero), 8);     /* zero the rest of the struct */
    
            if (connect(sockfd, (struct sockaddr *)&their_addr, \
                                                  sizeof(struct sockaddr)) == -1) {
                perror("connect");
                exit(1);
            }
    
            if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {
                perror("recv");
                exit(1);
            }
    
            buf[numbytes] = '\0';
    
            printf("Received: %s",buf);
    
            close(sockfd);
    
            return 0;
        }

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Go at it incrementally... small steps.... First get it to connect, then echo (type on client, echo from server), then open a file and store text (type on client, save on server)... just keep moving toward your goal with each new step.

    FWIW... resist the temptation to cut and paste code during the learning curve. You will learn far more --and forget far less-- if you sweat over every function call.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Especially when the copy/paste code is wrong
    Code:
            if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {
                perror("recv");
                exit(1);
            }
    
            buf[numbytes] = '\0';
    If the buffer is FULL, then the \0 is out of bounds.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Nov 2010
    Posts
    16
    Ok call me an idiot but I can't seem to locate the line where it takes the input from the console.

    If I can isolate that line I can use other code I have created and get the server working so that it fills the buffer with the search word and hopefully finds the address

  9. #9
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Obviously, you haven't written that code to get input from the console.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with sockets under linux
    By principii in forum Linux Programming
    Replies: 7
    Last Post: 10-20-2010, 02:31 AM
  2. (Where) learning linux tcp/ip sockets
    By codecaine_21 in forum Networking/Device Communication
    Replies: 4
    Last Post: 09-17-2010, 05:54 PM
  3. Get website content - C Sockets - Linux
    By daveoffy in forum C Programming
    Replies: 3
    Last Post: 02-17-2010, 10:01 AM
  4. writing dhcp client code using sockets on Linux
    By dash in forum Linux Programming
    Replies: 3
    Last Post: 08-04-2009, 10:20 AM
  5. HPUX sockets vs Linux?
    By cpjust in forum Linux Programming
    Replies: 4
    Last Post: 12-06-2007, 02:51 PM