src/irc.c
changeset 58 500a5ea7fcb8
parent 50 412ac658eb97
child 59 e8f15b159e19
equal deleted inserted replaced
57:ca4e10daa1c9 58:500a5ea7fcb8
    32     "TOPIC", "PING", "ENOMEM", "ERROR",
    32     "TOPIC", "PING", "ENOMEM", "ERROR",
    33     "VERSION", "PRIVMSG", "QUIT", "NICK",
    33     "VERSION", "PRIVMSG", "QUIT", "NICK",
    34     "KICK", NULL
    34     "KICK", NULL
    35 };
    35 };
    36 
    36 
    37 FILE *irc_connect (char *server, unsigned int port)
    37 FILE *irc_connect (char *server, char *port)
    38 {
    38 {
    39     struct hostent *he;
    39     struct addrinfo hints;
    40     char *ip;
    40     struct addrinfo *result, *rp;
    41     struct sockaddr_in ca;
    41 
    42     int csocket;
    42     int csocket = -1;
    43     FILE *stream;
    43     FILE *stream;
    44 
    44 
    45     he = gethostbyname (server);
    45     memset (&hints, 0, sizeof (struct addrinfo));
    46     if (he == NULL) {
    46     hints.ai_family = AF_UNSPEC;
    47         perror ("GETHOSTBYNAME");
    47     hints.ai_socktype = SOCK_STREAM;
       
    48     hints.ai_flags = 0;
       
    49     hints.ai_protocol = IPPROTO_TCP;
       
    50 
       
    51     if (getaddrinfo (server, port, &hints, &result) != 0) {
       
    52         perror ("getaddrinfo");
    48         return NULL;
    53         return NULL;
    49     }
    54     }
    50 
    55 
    51     if ((ip = inet_ntoa (*((struct in_addr *)he->h_addr_list[0]))) == NULL) {
    56     for (rp = result; rp != NULL; rp = rp->ai_next) {
    52         perror ("INET_NTOA");
    57         if ((csocket = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1)
    53         return NULL;
    58             continue;
    54     } else
    59 
    55         printf ("IP: %s\n", ip);
    60         if (connect (csocket, rp->ai_addr, rp->ai_addrlen) != -1) {
    56 
    61             fprintf (stderr, "Connected via %s\n", (rp->ai_family == AF_INET6) ? "IPv6" : "IPv4");
    57     ca.sin_family = AF_INET;
    62             break;
    58     ca.sin_addr.s_addr = inet_addr (ip);
    63         }
    59     ca.sin_port = htons (port);
    64         close (csocket);
    60 
    65     }
    61     csocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    66 
    62     if (connect (csocket, (struct sockaddr *)&ca, (socklen_t) sizeof (ca)) == -1) {
    67     if (result != NULL)
    63         perror ("CONNECT");
    68         freeaddrinfo (result);
       
    69 
       
    70     if (csocket < 0) {
       
    71         perror ("Cannot connect");
    64         return NULL;
    72         return NULL;
    65     }
    73     }
    66 
    74 
    67     /*
    75     /*
    68      * rw mode,but many seek errors ...
    76      * rw mode,but many seek errors ...