6

我正在尝试编写一个 C 程序来侦听我机器上的端口。我遇到了一个奇怪的错误。

每当我尝试将套接字绑定到固定 IP(127.0.0.1或我的实际 IP)时,都会出现"bind failed: Cannot assign requested address"错误。但是,当我将INADDR_ANY绑定作为要绑定的地址传递给绑定时,它可以工作。

这是我仅有的两个 IP,所以 0.0.0.0 不可能因为我有其他一些可用的 IP 地址而工作。

这是代码:

#include<sys/types.h>
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    int port = 1234;    /* port number */
    int rqst;       /* socket accepting the request */
    socklen_t alen;       /* length of address structure */
    struct sockaddr_in my_addr;    /* address of this service */
    struct sockaddr_in client_addr;  /* client's address */
    int sockoptval = 1;

    int svc;


    /* create a TCP/IP socket */
    if ((svc = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("cannot create socket");
        exit(1);
    }

    /* allow immediate reuse of the port */
    setsockopt(svc, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int));

    /* bind the socket to our source address */
    memset((char*)&my_addr, 0, sizeof(my_addr));  /* 0 out the structure */
    my_addr.sin_family = AF_INET;   /* address family */
    my_addr.sin_port = htons(port);
    //my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Works! */
    my_addr.sin_addr.s_addr = htonl(inet_addr("127.0.0.1")); /* Fails! */

    if (bind(svc, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0) {
        perror("bind failed");
        exit(1);
    }

    printf("Listening on %d\n", my_addr.sin_addr.s_addr);
    /* set the socket for listening (queue backlog of 5) */
    if (listen(svc, 5) < 0) {
        perror("listen failed");
        exit(1);
    }

    /* loop, accepting connection requests */
    for (;;) {
        while ((rqst = accept(svc, (struct sockaddr *)&client_addr, &alen)) < 0) {
            /* we may break out of accept if the system call */
                        /* was interrupted. In this case, loop back and */
                        /* try again */
                        if ((errno != ECHILD) && (errno != ERESTART) && (errno != EINTR)) {
                                perror("accept failed");
                                exit(1);
                        }
                }
        /* the socket for this accepted connection is rqst */
    }
}
4

1 回答 1

10

该函数inet_addr返回已经按网络顺序排列的地址:

inet_addr() 函数将 Internet 主机地址 cp 从 IPv4 数字和点表示法转换为网络字节顺序的二进制数据

所以放下htonl.

于 2013-03-18T22:26:14.677 回答