为什么将getaddrinfo与节点一起使用为NULL而ai_flags为PASSIVE会导致IP地址错误?

时间:2015-03-26 14:52:09

标签: c

为什么程序会将我的IP地址打印为0.0.0.0?如果我指定我的IP地址,它将是正确的IP。我在手册页中阅读了关于getaddrinfo的部分,并看到在代码中分配AI_PASSIVE和NULL是有效的。那么,这里有什么问题?

更新:为res和sa分配内存

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

#include "../cus_header/cus_header.h"

#define MYPORT "30000"
#define BACKLOG 10


int main(int argc, char *argv[]){

    struct addrinfo hints, *res;
    res = malloc(sizeof(struct addrinfo)); // update here
    char ip4[INET_ADDRSTRLEN];
    struct sockaddr_in *sa;
    sa = malloc(sizeof(struct sockaddr_in)); // update here

    // load up address struct with getaddrinfo
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    if(getaddrinfo(NULL, MYPORT, &hints, &res) == -1){
        error("Cannot get AI");
    }

    sa = (struct sockaddr_in*)res->ai_addr;

    inet_ntop(AF_INET, &(sa->sin_addr), ip4, INET_ADDRSTRLEN);
    printf("The IPv4 address is: %s\n", ip4);

    free(res); // update here
    free(sa); // update here

    return 0;

}

1 个答案:

答案 0 :(得分:0)

根据手册:

import numpy as np
from typing import Union, Sequence

def get_distances(self, 
                  position: Union[Sequence[int, int, int], np.ndarray((3,), dtype=int)]):
    ...
    return distances
  

如果在hints.ai_flags中指定了AI_PASSIVE标志,并且节点为NULL,则返回   套接字地址将适合于将接受(2)连接的套接字绑定(2)。   返回的套接字地址将包含“通配符地址”(用于IPv4的INADDR_ANY   地址,IN6ADDR_ANY_INIT为IPv6地址)。通配符地址由应用程序使用   (通常是服务器)打算接受任何主机网络上的连接   地址。如果node不为NULL,则AI_PASSIVE标志将被忽略。

所以0.0.0.0并不是一个错误的地址,而是通配符地址,即主机的任何地址。