getsockname return invalid address

2020-07-29 18:11发布

问题:

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

回答1:

You need to initialize the slen argument to getsockname() , and you should check its return value - so you can get more information if it fails.

slen = sizeof my_addr;
if (getsockname(udp_sockfd,(struct sockaddr*)&my_addr,&slen) != 0) {
   perror("getsockname");
}


回答2:

You can only use getsockname after 'connect' for client, 'accept' for server if you want to get the socket pair of the connection. You also need to initialize the variable len like this: len = sizeof my addr as @nos said. The function need the len to determine how long the (struct sockaddr*) is because we can pass a variable with the type of struct sockaddr_in, struct sockaddr_in6 or struct sock_storage. Those three kind of types have a different length.



标签: port