Can't bind to low port number (80) on XP sp3

I have this code in my socket class:

bool GSocket::Listen(int Port)
{
    d->Socket = socket(AF_INET, SOCK_STREAM, 0);
    if (d->Socket >= 0)
    {
        sockaddr Addr;
        sockaddr_in *a = (sockaddr_in*) &Addr;
        ZeroObj(Addr);
        a->sin_family = AF_INET;
        a->sin_port = htons(Port);
        a->sin_addr.OsAddr = INADDR_ANY;

        if (bind(d->Socket, &Addr, sizeof(Addr)) >= 0)
        {
            if (listen(d->Socket, SOMAXCONN) != SOCKET_ERROR)
            {
                return true;
            }
            else
            {
                Error();
            }
        }
        else
        {
            Error();
        }
    }
    else
    {
        Error();
    }

    return false;
}

      

The "Error ()" method raises a WSAGetLastError and passes the error and its description to the application. Anyway, it works fine on my machine (xp sp2), but doesn't work on my xp sp3 friends machine. In particular, the call to the binding fails and WSAGetLastError returns "2", which is not even a valid socket error code. The Port value passed in 80, I am using a simple HTTP server as the UI for the service. I'm not entirely sure why I'm checking for a value> = 0, but it might be related to non-Windows platforms. I am using this code as well. In any case, according to MSDN, the error return code for the binding is SOCKET_ERROR, which is -1 for the check to be fine.

Am I missing something simple?

Update: we just tried another port number "8888" and everything works as expected. So it seems that the low port number is the problem. Nothing active listening on this port until we start my service, so I think there are some new permissions in SP3 that stop processes listening on ports <1024 if they don't have specific permissions, similar to how linux / unix does it. However, I would like to sort it out anyway.

+1


source to share


2 answers


Port numbers in the range 0 to 1023 are known ports , and the operating system may need administrative privileges to bind to them, therefore, any application that tries to use these ports must be privileged.



+2


source


You're doing some fun pointer arithmetic ... just put sockaddr_in on the stack and pass a pointer to it to bind.

sockaddr_in a = {0};
a.sin_family = AF_INET;
a.sin_port = htons(Port);
a.sin_addr.OsAddr = INADDR_ANY;

if (bind(d->Socket, (sockaddr *) &a, sizeof(a)) >= 0)

      



Also, try checking if privileges are getting in the way. Is there something open already on this port (ask netstat)

0


source







All Articles