I'm trying to bind 256 different sockets in 256 different pthread's to different ports by passing 0 port value to socket bind function. But sometimes same port gets bound to different sockets. I found this issue from debug output. Can somebody explain why this is happening. This is my sample code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
unsigned short get_sock_name(int sock_fd) {
socklen_t sock_len = sizeof(struct sockaddr_in);
struct sockaddr_in recv_IP_sock_addr;
getsockname(sock_fd, (struct sockaddr*)&recv_IP_sock_addr, &sock_len);
return (ntohs(recv_IP_sock_addr.sin_port));
}
void* run(void *t) {
int sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);;
struct sockaddr_in recv_IP_sock_addr;
memset((char*)&recv_IP_sock_addr, '\0', sizeof(struct sockaddr_in));
recv_IP_sock_addr.sin_family = AF_INET;
recv_IP_sock_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
recv_IP_sock_addr.sin_port = htons(0);
int yes = 1;
setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
bind(sock_fd, (struct sockaddr*)&recv_IP_sock_addr, sizeof(struct sockaddr));
unsigned short port = get_sock_name(sock_fd);
printf("receiving data from port %hu\n", port);
char buff[2048];
while (1) {
ssize_t len = recvfrom(sock_fd, buff, sizeof(buff), 0, NULL, NULL);
}
}
int main() {
pthread_t pt_arr[256];
for (int i = 0; i < 256; i)
pthread_create(&pt_arr[i], NULL, run, NULL);
char buff[32];
fgets(buff, sizeof(buff), stdin);
}
CodePudding user response:
You set SO_REUSEADDR which, for UDP, permits two sockets to bind to the same port. This is needed for multicast. Using it with unicast UDP doesn't seem to be a particularly good idea. Using it when letting the implementation select the port doesn't seem like a good idea either.
Get rid of SO_REUSEADDR as it makes no sense and causes pathological behavior with UDP unicast.
