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));
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));
Share
Improve this question
asked Mar 20 at 11:54
MaxAMaxA
135 bronze badges
9
|
Show 4 more comments
1 Answer
Reset to default 2You 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.
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? – Richard Critten Commented Mar 20 at 12:01"the bind fails"
isn't a very useful problem description. What is the error? Is192.168.1.11
a valid local address? – G.M. Commented Mar 20 at 12:01...s_addr = inet_addr(ip_addr.c_str());
with...s_addr = INADDR_ANY;
? – G.M. Commented Mar 20 at 12:24