perlperl
asked on
socket bind convert ipv4 to support both ipv4 and ipv6
What is the difference between these two bind methods?
1. In the first one I am setting sin_addr to 0 and the application was accepting IPv4 only.
2. in the second one I am using getaddrinfo as I need to start listening on IPv6 also.
Case 1 is older code and I am not sure why the sin_addr was set to 0 and not the actual ip address of server. I need to convert to support ipv6 also but not sure if i convert to getaddrinfo, i would break something?
1. In the first one I am setting sin_addr to 0 and the application was accepting IPv4 only.
2. in the second one I am using getaddrinfo as I need to start listening on IPv6 also.
Case 1 is older code and I am not sure why the sin_addr was set to 0 and not the actual ip address of server. I need to convert to support ipv6 also but not sure if i convert to getaddrinfo, i would break something?
/************ METHOD 1 **********/
int fd;
int sock_type = SOCK_STREAM;
if ((fd = socket(AF_INET, sock_type, IPPROTO_TCP)) < 0) {
// ERROR
}
int port = 5000;
struct sockaddr_in sin;
memset((char *)&sin, 0, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0; // SET to ZERO
sin.sin_port = htons(port);
while (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
// sleep for fews and retry and succeed
}
/********************* METHOD 2 ***************/
struct addrinfo hints, *start, *results;
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, "5000", &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);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.