连接拒绝连接到1234以外的任何端口

时间:2016-03-28 23:29:40

标签: c linux sockets port host

我正在开发一个连接到主机和端口的聊天机器人。虽然,只要我连接到“1234”以外的任何端口,我都会收到connect: Connection refused错误。这似乎是由套接字引起的,为什么它只连接到单个端口的任何想法?

#include <stdio.h>
//#include "parse.h"
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>

int choice(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
       struct timeval *timeout) {
    int n = select(nfds, readfds, writefds, exceptfds, timeout);
    if (n < 0) {
        perror("select");
        exit(1);
    }
    return(n);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "usage: %s hostname [port number] ...\n", argv[0]);
        return(1);
    }

    int sockfd;
    char buf[500];
    struct hostent *hp;
    struct sockaddr_in peer;
    fd_set master;
    peer.sin_family = AF_INET;

    if (argc == 2) {
        peer.sin_port = htons(1234);
    } else {
        peer.sin_port = htons(atoi(argv[2]));
    }


    //HOST
    if ((hp = gethostbyname(argv[1])) == NULL) {
        fprintf(stderr, "%s: no such host\n", argv[1]);
        return(1);
    }

    if (hp->h_addr_list[0] == NULL || hp->h_addrtype != AF_INET) {
        fprintf(stderr, "%s: not an internet protocol host name\n", argv[1]);
        return(1);
    }

    //SOCKET
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (connect(sockfd, (struct sockaddr *)&peer, sizeof(peer)) == -1) {
        perror("connect");
        close(sockfd);
        exit(1);
    }

    FD_ZERO(&master);
    FD_SET(STDIN_FILENO, &master);
    FD_SET(sockfd, &master);
    fd_set fds = master;

    //LOOP
    while(1) {
        choice(sockfd+1, &fds ,NULL,NULL,NULL);
        if(FD_ISSET(STDIN_FILENO, &fds)) {
            fgets(buf, sizeof buf, stdin);
            if (strlen(buf) > 0) { 
                printf("success");
                /*
                struct expr *e = parse(buf);
                if (e) {
                    printf("Hey XXX, %d\n", evalexpr(e));
                    freeexpr(e);
                } else {
                    printf("Hey XXX, I don't like that.\n[%s]\n", errorstatus);
                } */
            }
        }
    }
}

我注释掉了一段需要额外代码的代码,以保持代码最小化和可复制(?)。我应该能够连接到1235,20000,25000等端口

1 个答案:

答案 0 :(得分:1)

您正在查找主机名,但您永远不会将生成的IP地址转移到peer,因此您实际上并未连接到主机。你需要添加这个:

peer.sin_addr = *((struct in_addr*)(hp->h_addr_list[0]));