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

Connection refused connecting to any port other than 1234

我正在开发一个连接到主机和端口的聊天机器人。虽然,每当我连接到“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等端口

您正在查找主机名,但您从未将生成的 IP 地址传输到 peer,因此您实际上并未连接到主机。您需要添加:

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