int get_free_port()
{
int port = 0;
int fd = -1;
socklen_t = 0;
port = -1;
#ifndef AF_IPV6
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(0);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(fd < 0){
printf("socket() error:%s\n", strerror(errno));
return -1;
}
if(bind(fd, (struct sockaddr *)&sin, sizeof(sin)) != 0)
{
printf("bind() error:%s\n", strerror(errno));
close(fd);
return -1;
}
len = sizeof(sin);
if(getsockname(fd, (struct sockaddr *)&sin, &len) != 0)
{
printf("getsockname() error:%s\n", strerror(errno));
close(fd);
return -1;
}
port = sin.sin_port;
if(fd != -1)
close(fd);
#else
struct sockaddr_in6 sin6;
memset(&sin6, 0, sizeof(sin6));
sin.sin_family = AF_INET6;
sin.sin_port = htons(0);
sin6.sin_addr.s_addr = htonl(IN6ADDR_ANY);
fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if(fd < 0){
printf("socket() error:%s\n", strerror(errno));
return -1;
}
if(bind(fd, (struct sockaddr *)&sin6, sizeof(sin6)) != 0)
{
printf("bind() error:%s\n", strerror(errno));
close(fd);
return -1;
}
len = sizeof(sin6);
if(getsockname(fd, (struct sockaddr *)&sin6, &len) != 0)
{
printf("getsockname() error:%s\n", strerror(errno));
close(fd);
return -1;
}
port = sin6.sin6_port;
if(fd != -1)
close(fd);
#endif
return port;
}
|