Getting ip server 0.0.0.0:07 from getaddrinfo ()

I follow Bay's NP manual.

I made some changes and am trying to get the IP address of my server program through getaddrinfo ().
(the original can be found here http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#simpleserver )

Below are the parts that I changed / added.

if ((rv = getaddrinfo(NULL, "0", &hints, &servinfo)) != 0) { //0 for random port?
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
 }

//... some code emitted ...

//freeaddrinfo(servinfo); //I still need it!


printf("ip: %s\nport: %d\n",
    inet_ntop(AF_INET, &((struct sockaddr_in *)p->ai_addr)->sin_addr, ip4, INET_ADDRSTRLEN),
    ntohs(((struct sockaddr_in *)p->ai_addr)->sin_port)
);

The problem is that I get results

ip: 0.0.0.0  
port: 0  

Q1: I read from several websites saying that setting “0” for the port tells the OS that you want the next available port, and not really 0. Is that true?

Q2: I also read that gethostbyname (gethostname (...)) can give you an ip machine, but Beej said that they are replaced by getaddrinfo (). So should I use getaddrinfo? Or gethostbyname?

Q3: - , ?

+5
2

Q1: -, , "0" , , 0. ?

, , bind() . getsockname(), ; .

Q2: , gethostbyname (gethostname (...)) ip, Beej , getaddrinfo(). , getaddrinfo? gethostbyname?

getaddrinfo(); , gethostbyname() , . (, .)

Q3: - , ?

IP- . - , ( , ), , , ( NAT). , , - , localhost, , bind(), . , getpeername(), NAT . .

, . - , .

+6

, .

man getaddrinfo:

AI_PASSIVE hints.ai_flags, node NULL, (2) , (2) . " " (INADDR_ANY IPv4, IN6ADDR_ANY_INIT IPv6). wild-card ( ), . node NULL, AI_PASSIVE .

, , hints.ai_flags AI_PASSIVE, NULL node. 0.0.0.0. . , IP- .

... "0", ... , . , , , .

+8

All Articles