i used fork to create a bunch of children, in each child, create a UDP port and send it back to the parent by TCP, but the problem is that when the number of children increased to 9, the getsockname() function returns port num 0 for each child.
int udp_sockfd;
struct sockaddr_in their_addr, my_addr;
socklen_t slen;//used in getsockname()
if((udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(0);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), sizeof(my_addr.sin_zero));
if(bind(udp_sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
getsockname(udp_sockfd,(struct sockaddr*)&my_addr,&slen);
printf("client %d: my port number: %d\n",i,my_addr.sin_port);
when there are 8 children, the result is correct