我用叉子來創建一羣孩子,在每個孩子身上,創建一個UDP端口並通過TCP發回給父母,但問題是當孩子的數量增加到9時, getsockname()函數爲每個子項返回端口num 0。getsockname返回無效地址
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);
時,有8個孩子,結果是正確的