potato.h
/* This function finds an avaiable server address with host and port_num,
   and returns a socket fd which connects to the address */
This function finds an avaiable server address with host and port_num,
and returns a socket fd which connects to the address
This function finds an avaiable server address with host and port_num and returns a socket fd which connects to the address
int socket_and_connect(const char * host, const char * port_num) {
  int status;
  int server_fd;
  struct addrinfo hints;
  struct addrinfo * addr_info_list;  
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;      
  hints.ai_socktype = SOCK_STREAM;  
  hints.ai_flags = AI_NUMERICSERV;
  status = getaddrinfo(host, port_num, &hints, &addr_info_list);
  if (status != 0) {
    return -1;
  }
  struct addrinfo * curr;
  for (curr = addr_info_list; curr != NULL; curr = curr->ai_next) {
    server_fd = socket(curr->ai_family, curr->ai_socktype, curr->ai_protocol);
    if (server_fd == -1) {
      continue;  
    }
    status = connect(server_fd, curr->ai_addr, curr->ai_addrlen);
    if (status == 0) {
      break;  
    }
    else {  
      checkedClose(server_fd);
    }
  }
  freeaddrinfo(addr_info_list);  
  if (curr == NULL) {
    return -1;
  }
  return server_fd;
}
int socket_and_connect ( const char * host , const char * port_num ) { int status ; int server_fd ; struct addrinfo hints ; struct addrinfo * addr_info_list ; memset ( & hints , 0 , sizeof ( hints ) ) ; hints . ai_family = AF_UNSPEC ; hints . ai_socktype = SOCK_STREAM ; hints . ai_flags = AI_NUMERICSERV ; status = getaddrinfo ( host , port_num , & hints , & addr_info_list ) ; if ( status != 0 ) { return -1 ; } struct addrinfo * curr ; for ( curr = addr_info_list ; curr != NULL ; curr = curr -> ai_next ) { server_fd = socket ( curr -> ai_family , curr -> ai_socktype , curr -> ai_protocol ) ; if ( server_fd == -1 ) { continue ; } status = connect ( server_fd , curr -> ai_addr , curr -> ai_addrlen ) ; if ( status == 0 ) { break ; } else { checkedClose ( server_fd ) ; } } freeaddrinfo ( addr_info_list ) ; if ( curr == NULL ) { return -1 ; } return server_fd ; }
This function finds an avaiable server address with host and port_num,
and returns a socket fd which connects to the address
This function finds an avaiable server address with host and port_num and returns a socket fd which connects to the address
/* Get the connectable address list with machine_name & port_num */ // head of the addr info list // Searching IPv4 and IPv6 // TCP /* Iterate the returned address list to find one to which we
    one successfully connect */ // Create socket failed, try next address // connect() succeed // connect() failed, close the socket and try next address // Free dynamically allocated space