Thank you for being a valued part of the CNET community. As of December 1, 2020, the forums are in read-only format. In early 2021, CNET Forums will no longer be available. We are grateful for the participation and advice you have provided to one another over the years.

Thanks,

CNET Support

Question

EAFNOSUPPORT (Address Family not supported) on sendto()

Sep 25, 2018 7:13PM PDT

Hello,

I am trying to send a message over a UDP socket connection I setup. The server connection is successful as reported by the system calls. However the sendto() system call fails with EAFNOSUPPORT (Address Family not Supported; err = 97)

Here is my code
int connection()
{
char *ip = (char *)"xx.xxx.xx.xxx";
int port = 1499;

struct sockaddr_in sockaddr;
socklen_t addrlen = sizeof(sockaddr);

udp_fd = socket(AF_INET, SOCK_DGRAM, 0);

if (udp_fd == -1) {
printf("Could not create socket\n");
return -1;
}

x = 1;
rc = setsockopt (udp_fd, SOL_SOCKET, SO_REUSEPORT, &x, sizeof (x));
if (rc == -1) {
printf("setsockopt port opt failed\n");
return -1;
}
rc = setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof (x));
if (rc == -1) {
printf("setsockopt adrr opt failed\n");
return -1;
}

rc = setsockopt (udp_fd, SOL_SOCKET, SO_BROADCAST, &o_broadcast, sizeof (o_broadcast));
if (rc == -1) {
printf("setsockopt broadcast opt failed\n");
return -1;
}

bzero(&sockaddr, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(ip);
sockaddr.sin_port = htons(port);


if (fcntl(udp_fd, F_SETFL, O_NONBLOCK | O_ASYNC) < 0) {
printf("Error setting socket as non-blocking \n");
return -1;
}

if (connect(udp_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == -1) {
printf("Could not connect to %s: %d: %d: %d\n", ip, port, errno, udp_fd);
return -1;
}

printf("Success connecting to server\n");

return 1;
}

The above is successful.

And here is my sendto() call that fails with EAFNOSUPPORT (err=97)

int len = sizeof(command);
bytes_sent = sendto(udp_fd, command, len, 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
if (bytes_sent < 0) {
printf("Could not send message to %d: errorr=%d with %d bytes \n", udp_fd, errno, bytes_sent);
}

Can anyone help me understand what I am doing wrong here ?

The remote address is outside of the subnet of my localhost where I run this program.

Discussion is locked

- Collapse -
Clarification Request
Port 1499 might not be open to accept UDP messages
Sep 25, 2018 8:08PM PDT

The port 1499 does not seem to be open to accept UDP packet messages.

Is that a possible reason why I get the EAFNOSUPPORT error here ? It does seem vague if so.

- Collapse -
Answer
bad struct sockaddr_in
Sep 26, 2018 3:22PM PDT

I had a bad struct sockaddr_in that I think was causing the error. I moved the setting of the struct to the local function and it seems to work now.