c++udpwinsock2

C++ Winsock UDP Port Wont Bind


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));

Solution

  • 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.