TheAbelo2 TheAbelo2 - 24 days ago 7
C++ Question

Set hostname using winsock?

I've just started using winsock, and it seems like it's only making a server on the local machine by default, rather than accepting external connections (from other computers on the system). I'm looking for the C++ equivalent of

socket.bind(("192.168.0.112", 1024))
in Python (rather than
"localhost"
)

Answer

If you want to bind to all adapters, which is the most common thing to do for accepting connections from both localhost and remote addresses, then this is all you really have to do:

sock = socket(AF_INET, SOCK_STREAM, 0);    // SOCK_STREAM==TCP.  Use SOCK_DGRAM if you want UDP

sockaddr_in addr = {};         // ={} is zero-init.  Since INADDR_ANY is 0, it implicitly sets this as well
addr.sin_family = AF_INET;
addr.sin_port = htons(1024);   // port 1024 in network byte order

int result = bind(sock, (sockaddr*)&addr, sizeof(addr));
Comments