Thread: Socket code problems

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    11

    Socket code problems

    When I run this program, everything works as expected. It starts up and connects to a server and gets all the stuff the server is supposed to send. However, when I try to type something, it works, but then it won't listen to any more input and I don't think it recieves any more. I have no idea why.
    Code:
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <errno.h>
     
    #define SOCKET_ERROR        -1
    #define BUFFER_SIZE         100
    #define HOST_NAME_SIZE      255
     
    int  main(int argc, char* argv[])
    {
        int hSocket;                 /* handle to socket */
        struct hostent* pHostInfo;   /* holds info about a machine */
        struct sockaddr_in Address;  /* Internet socket address stuct */
        long nHostAddress;
        char pBuffer[BUFFER_SIZE];
        unsigned nReadAmount;
        char strHostName[HOST_NAME_SIZE];
        int nHostPort;
        char buf[1024];
        int n;
     
        if(argc < 3)
          {
            printf("\nUsage: client host-name host-port\n");
            return 0;
          }
        else
          {
            strcpy(strHostName,argv[1]);
            nHostPort=atoi(argv[2]);
          }
     
        /* make a socket */
        hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     
        if(hSocket == SOCKET_ERROR)
        {
            printf("\nCould not make a socket\n");
            return 0;
        }
     
        /* get IP address from name */
        pHostInfo=gethostbyname(strHostName);
        /* copy address into long */
        memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);
     
        /* fill address struct */
        Address.sin_addr.s_addr=nHostAddress;
        Address.sin_port=htons(nHostPort);
        Address.sin_family=AF_INET;
    printf("Connecting to %s on port %d\n",strHostName,nHostPort);
     
        /* connect to host */
        if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address)) 
           == SOCKET_ERROR)
        {
            printf("\nCould not connect to host\n");
            return 0;
        }
     
        /* read from socket into buffer
        ** number returned by read() and write() is the number of bytes
        ** read or written, with -1 being that an error occured */
        printf("Type a ~ to exit\n");
        printf("Enter to continue\n");
    while(1)
        {
            gets(buf);
            if(buf[0] == '~')
                break;
            n = strlen(buf);
            buf[n] = '\n';
            buf[n+1] = 0;
            write(hSocket,buf, strlen(buf));
            nReadAmount = 1;
            while(nReadAmount > 0)
            {
                nReadAmount=read(hSocket,pBuffer,BUFFER_SIZE);
                pBuffer[nReadAmount] = '\0';
                printf("%s", pBuffer);
            }
            printf("\n>");
        }
        /* write what we received back to the server */
     
        printf("\nClosing socket\n");
        /* close socket */                       
        if(close(hSocket) == SOCKET_ERROR)
        {
            printf("\nCould not close socket\n");
            return 0;
        }
    }
    Last edited by Phan; 09-12-2005 at 11:30 PM.

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Wouldn't it be more appropriate to post this in the Networking/Device Communication or the Linux Programming forums?

  3. #3
    FOX
    Join Date
    May 2005
    Posts
    188
    Didn't anyone tell you to never ever use gets()?

  4. #4
    Registered User
    Join Date
    Jul 2005
    Posts
    11
    Quote Originally Posted by cwr
    Wouldn't it be more appropriate to post this in the Networking/Device Communication or the Linux Programming forums?
    Yes, I accidently posted this is C. My mistake.

    Quote Originally Posted by ^xor
    Didn't anyone tell you to never ever use gets()?
    Is get(); the thing that messes up my code?

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    moved
    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.

  6. #6
    FOX
    Join Date
    May 2005
    Posts
    188
    Quote Originally Posted by Phan
    Is get(); the thing that messes up my code?
    It's gets() and not get(), and I haven't looked closely at your code so I don't know if that's what causing it to break. But the mere presence of it in your code means that your program has a vulnerability, so use fgets or something similar.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > I have no idea why.
    Well
    nReadAmount=read(hSocket,pBuffer,BUFFER_SIZE);
    has no idea how long to wait before deciding there is no more data to be read - it returns 0 when the socket closes.

    So you need to make the read() non-blocking somehow (depends on your OS). But in Linux, I would use select() with a timeout to determine whether was anything interesting to be read.
    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
    Jul 2005
    Posts
    11
    Does read return anything if there is nothing more to read? Because I've currently been trying something like this:

    Code:
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <errno.h>
     
    #define SOCKET_ERROR        -1
    #define BUFFER_SIZE         100
    #define HOST_NAME_SIZE      255
     
    int  main(int argc, char* argv[])
    {
        int hSocket;                 /* handle to socket */
        struct hostent* pHostInfo;   /* holds info about a machine */
        struct sockaddr_in Address;  /* Internet socket address stuct */
        long nHostAddress;
        char pBuffer[BUFFER_SIZE];
        unsigned nReadAmount;
        char strHostName[HOST_NAME_SIZE];
        int nHostPort;
        char buf[1024];
        int n;
     
        if(argc < 3)
          {
            printf("\nUsage: client host-name host-port\n");
            return 0;
          }
        else
          {
            strcpy(strHostName,argv[1]);
            nHostPort=atoi(argv[2]);
          }
     
        /* make a socket */
        hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     
        if(hSocket == SOCKET_ERROR)
        {
            printf("\nCould not make a socket\n");
            return 0;
        }
     
        /* get IP address from name */
        pHostInfo=gethostbyname(strHostName);
        /* copy address into long */
        memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);
     
        /* fill address struct */
        Address.sin_addr.s_addr=nHostAddress;
        Address.sin_port=htons(nHostPort);
        Address.sin_family=AF_INET;
    printf("Connecting to %s on port %d\n",strHostName,nHostPort);
     
        /* connect to host */
        if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address)) 
           == SOCKET_ERROR)
        {
            printf("\nCould not connect to host\n");
            return 0;
        }
     
        /* read from socket into buffer
        ** number returned by read() and write() is the number of bytes
        ** read or written, with -1 being that an error occured */
        printf("Type a ~ to exit\n");
       nReadAmount=1;
     while(nReadAmount > 0)
            {
                nReadAmount=recv(hSocket,pBuffer,BUFFER_SIZE,0);
                pBuffer[nReadAmount] = '\0';
                if (pBuffer[nReadAmount]='\0') {
                nReadAmount = 0;
                break;
                
                } else
                {
                
                printf("%s", pBuffer);
            }
            }
    
    
    while(nReadAmount = 0)
        {
            printf("\n>");
            gets(buf);
            if(buf[0] == '~')
                break;
            n = strlen(buf);
            buf[n] = '\n';
            buf[n+1] = 0;
            send(hSocket,buf, strlen(buf),0);
            nReadAmount = 1;
            break;
        }
        /* write what we received back to the server */
    
        printf("\nClosing socket\n");
        /* close socket */                       
        if(close(hSocket) == SOCKET_ERROR)
        {
            printf("\nCould not close socket\n");
            return 0;
        }
    }
    There isn't any thing wrong with it that I can see, excpet for the fact that I think I'm not getting the:
    if (pBuffer[nReadAmount]='\0') {
    nReadAmount = 0;
    part right. Ideas?

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Well
    > if (pBuffer[nReadAmount]='\0')
    > while(nReadAmount = 0)
    are assignments, not comparisons, so who knows what's going on.

    AFAIK, read() only returns 0 when the socket closes, not when there's nothing to read.

    That is, unless you've made the socket non-blocking.
    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.

  10. #10
    Registered User
    Join Date
    Jul 2005
    Posts
    11
    Ok, so I should probably use select then with a timeout. How would select() be used in a situation like this? select(blah, &readfds, NULL,NULL,&timeout); ?

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with compiling code in cygwin
    By firyace in forum C++ Programming
    Replies: 4
    Last Post: 06-01-2007, 08:16 AM
  2. Problems with code from the FAQ
    By Bhaunted in forum C++ Programming
    Replies: 1
    Last Post: 08-31-2004, 02:36 PM
  3. structs, array, code has problems, Im lost
    By rake in forum C++ Programming
    Replies: 4
    Last Post: 03-13-2002, 02:02 AM
  4. problems with output from code
    By simhap in forum C++ Programming
    Replies: 0
    Last Post: 10-08-2001, 12:43 PM
  5. Socket Problems
    By (TNT) in forum Windows Programming
    Replies: 4
    Last Post: 08-18-2001, 06:59 AM