C socket woes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Xx r3negade
    New Member
    • Apr 2008
    • 39

    C socket woes

    I am having trouble using connect() when entering struct addrinfo members as parameters.

    Code:
    int tcpConnect()
    {
        struct addrinfo hints;
        struct addrinfo *ai = NULL;
        int res;
        int sock1;
        char * ipaddr = "127.0.0.1";
        char * port = "80";
    
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
    
        if ( (res = getaddrinfo(ipaddr, port, &hints, &ai)) < 0 )
        {
            fprintf(stderr, "Error in getaddrinfo(): %s", gai_strerror(res));
            return -1;
        }
    
        if ( (sock1 = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0 )
        {
            fprintf(stderr, "Error in socket(): %s", gai_strerror(res));
            return -1;
        }
    
        if ( (res = connect(sock1, ai->ai_addr, ai->ai_addrlen)) < 0 )
        {
            fprintf(stderr, "Error in connect(): %s", gai_strerror(res));
            return -1;
        }
    
        return 0;
    }
    It outputs the error:
    Code:
    Error in connect(): Bad value for ai_flags
    Do I need to set something for ai_flags in the "hints" struct? Or is getaddrinfo() giving a bad value to ai_flags in the "ai" struct?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by Xx r3negade
    It outputs the error:
    Code:
    Error in connect(): Bad value for ai_flags
    Do I need to set something for ai_flags in the "hints" struct? Or is getaddrinfo() giving a bad value to ai_flags in the "ai" struct?
    That flag member is an input value to that function; try to set it to AI_PASSIVE and see what happens.

    kind regards,

    Jos

    Comment

    • Xx r3negade
      New Member
      • Apr 2008
      • 39

      #3
      That isn't right. AI_PASSIVE is for use with bind() and listen(), not connect()

      iSeries Information Center

      If the AI_PASSIVE flag is specified, then the returned address information will be suitable for use in binding a socket for accepting incoming connections for the specified service (that is, a call to bind())...If the AI_PASSIVE bit is not set, the returned address information will be suitable for a call to connect()
      Edit: My code was correct. My firewall was configured to not accept connections from localhost. I don't know what's up with the irrelevant error messages, but the problem is now fixed. Thanks for the help anyway

      Comment

      Working...