在TCP端口上侦听时没有任何反应

时间:2016-09-20 23:36:10

标签: c sockets tcp

我正在尝试编写一个小型示例应用程序来侦听TCP端口,但由于某种原因它无法运行。

它看起来似乎达到accept(3p),但lsof -i :1080报告没有任何内容正在侦听该端口。没有任何错误或其他任何明显的错误。

任何提示?

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

const int THREADS = 4;
const int BUFFER_SIZE = 256;

void usage(char *app_name) {
    printf("Usage: %s PORT\n", app_name);
}

int main(int argc, char **argv) {
    struct sockaddr_in6 serv_addr, addr_cli;
    char buffer[BUFFER_SIZE];
    int sockfd, sock_cli, n, port;

    if (argc < 2) {
        usage(argv[0]);
        return -1;
    }

    port = atoi(argv[1]);

    if ((sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
        perror("Could not open socket");
        return errno;
    }

    serv_addr.sin6_family = AF_INET6;
    serv_addr.sin6_port = htonl(port);
    // other addresses: INADDR_LOOPBACK, INADDR_ANY
    serv_addr.sin6_addr = in6addr_any;
    serv_addr.sin6_scope_id = 0;

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) != 0) {
        perror("Could not bind to socket");
        return errno;
    }

    if (listen(sockfd, THREADS + 1) < 0) {
        perror("Could not listen to socket");
        return errno;
    }

    printf("Listening on :%d\n", port);

    unsigned long l;
    if ((sock_cli = accept(sockfd, (struct sockaddr *) &addr_cli, (socklen_t*) &l)) != 0) {
        perror("Could not accept connections on socket");
        return errno;
    }

    printf("Connection accepted\n");

    while ((n = recv(sock_cli, buffer, BUFFER_SIZE, 0)) > 0) {
        printf("> Got data: %s\n", buffer);
    }

    if (n < 0) {
        printf("Could not receive data\n");
        return errno;
    }

    printf("Bye!\n");
}

1 个答案:

答案 0 :(得分:1)

我让你的程序工作

$ ./hugo 8888 &
[1] 25330
$ Listening on :8888
telnet -6 localhost 8888
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Connection accepted
hello 
> Got data: hello
^]
telnet> quit
Connection closed.
Bye!
[1]+  Exit 10                 ./hugo 8888

进行以下更改:

#include <netinet/in.h>
...
serv_addr.sin6_port = htons(port);
...
if ((sock_cli = accept(sockfd,  
                       (struct sockaddr *) &addr_cli, 
                       (socklen_t*) &l)) == -1) {

如评论所示, htons (3)会导致收听正确的端口。并且接受(2)返回一个套接字,因此您明确地为-1进行了测试。

如果我可以提出两件小事,

  • main返回EXIT_SUCCESS。 :-)
  • 使用错误(3)代替 perror (3)。减少打字,你真的不想回归errno