Link to home
Start Free TrialLog in
Avatar of perlperl
perlperl

asked on

getaddrinfo and bind

struct addrinfo hints, *start, *results;
char* str_port = // some port that I receive from different function
	bzero(&hints, sizeof(struct addrinfo));
	hints.ai_flags = AI_PASSIVE; // Use address return by getaddrinfo in bind() return addrinfo will have INADDR_ANY set to IPv4 adress and INADDR6_ANY_INIT for IPv6 address
	hints.ai_family = AF_UNSPEC;  // return both the family AF_INET and AF_INET6 address structures
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
        

        getaddrinfo(NULL, str_port, &hints, &results));

start = results;
	do {
		if (results->ai_family == AF_INET || results->ai_family == AF_INET6 ) {
                      int  fd = socket(results->ai_family, results->ai_socktype, results->ai_protocol)

                      while (bind(fd, results->ai_addr, results->ai_addrlen)  < 0) {
                          // sleep for fews and retry and succeed
                     }
                     break;
               }
         } while ( (results=results->ai_next) != NULL);

Open in new window


The above code creates and bind a socket to port "str_port". Also it binds to all interfaces since I have provided flag AF_PASSIVE.

The above is called multiple times with various port number that I need to bind to all interfaces.
If for a specific port I need to bind to localhost only (both ipv4 and ipv6 socket), how can I achieve that.


Is there a different flag I need to use other than AF_PASSIVE or do I need to change the address results->ai_addr just before calling the bind?
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of perlperl
perlperl

ASKER

Oh i see, i just have to remove the line and this should bind to loopback (localhost) asdress only which will prevent external connection.

hints.ai_flag = AI_PASSIVE

Thanks!!!!!!!
Correct.

Or if you want to make it explicit you can do
hints.ai_flag = 0;

Open in new window

(But yeah, removing that line totally has the same effect because you "bzero" your hints struct on the line before it anyway)