-2

I'm writing a bit of code that can listen for UDP messages via Winsock. The port bind works on local loopback (127.0.0.1) but when I try to change to any other IP the bind fails.

Is there something I'm missing?

int socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

sockaddr_in receive_port;
memset(&receive_port, 0, sizeof(receive_port));
std::string ip_addr = "192.168.1.11";
receive_port.sin_addr.s_addr = inet_addr(ip_addr.c_str());
receive_port.sin_family = AF_INET;
receive_port.sin_port = htons(4000);

const char optval = 1;
int result = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int));
int bind_result = bind(socket_, (const struct sockaddr*)&receive_port, sizeof(receive_port));
9
  • 1
    Is 192.168.1.11 the address of your computer? Does the port need permissions from the default Windows firewall? What is the error code you get? Commented Mar 20 at 12:01
  • 2
    "the bind fails" isn't a very useful problem description. What is the error? Is 192.168.1.11 a valid local address? Commented Mar 20 at 12:01
  • Please provide an error message for clarification and what are you trying to achieve. Commented Mar 20 at 12:05
  • What happens if you replace ...s_addr = inet_addr(ip_addr.c_str()); with ...s_addr = INADDR_ANY;? Commented Mar 20 at 12:24
  • Thanks for the replies! I get a 10049 error so does this mean the IP isn't valid? In practice this will be ran on one PC on a local network receiving UDP messages from another PC on the same network. The IP and port should be valid where it's being ran but the bind still fails. However, it still works on 127.0.0.1. Commented Mar 20 at 12:29

1 Answer 1

2

You can only bind a port to interface addresses that belong to the local PC that is running your program.

However, INADDR_ANY (0.0.0.0) is almost always the right thing to use, unless for some complex reason you want to only receive packets on one of your interfaces, and you have more than one. If you are just on an ordinary system plugged into one ethernet cable/wifi, using ANY is easiest.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.