Search code examples
csocketsbindlisten

Cannot bind TCP socket to local IP


I have my server program binding fine to 0.0.0.0 (INADDR_ANY) or 127.0.0.1 (INADDR_LOOPBACK), however I want the program to listen on my local network IP (192.168.1.24) and I keep getting this error:

Error opening the listening port 8888 (Raw TCP output): Cannot assign requested address

Here is the relevant code:

#define LOCAL_IP ((unsigned long int) 0x1801A8C8) //192.168.1.24
#define PORT 8888

struct sockaddr_in sa;

sa.sin_family = AF_INET;
sa.sin_port = htons(PORT);
sa.sin_addr.s_addr = LOCAL_IP; /* Bind servers to local net*/
//sa.sin_addr.s_addr = htonl(INADDR_ANY);

I've also tried htonl(LOCAL_IP) and inet_addr("192.168.1.24") with no luck.


Solution

  • The IP you use is: 200.168.1.24

    Use:

    sa.sin_addr.s_addr = inet_addr("192.168.1.24");
    

    instead.
    Make sure the port isn't already in use. (use the program netstat) Have you closed the socket correctly, at tests before?