Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Negative port numbers when binding to port 0.

Name: Anonymous 2006-04-11 20:18

In this code fragment from a server program (edited for length):

sendPort = (short) desiredSendPort;
  
sendSock = socket(AF_INET, SOCK_STREAM, 0);

sendAddr.sin_family = AF_INET;
sendAddr.sin_addr.s_addr = INADDR_ANY;
sendAddr.sin_port = sendPort;

bind(sendSock, (struct sockaddr *) &sendAddr, sizeof(sendAddr)));
   
if (sendPort == 0) {
    length = sizeof(sendSock);
    getsockname(sendSock, (struct sockaddr *)&sendAddr, (unsigned int *) &length) < 0)
    sendPort = ntohs(sendAddr.sin_port);
}

When the port number is 0 the system assigns a negative number on the schools server, but a regular >1024 port number on my local Debian system. If you specify a port number it assigns properly on my Debian system but the school server denies permssion. Even if you specify something like 55739 the school server won't give up the port.

When using the program if you specify the negative number returned by the school server all the client programs work fine.

I'm using kernel 2.4.27 and the server is using 2.6.11.

Can anyone tell me possibly why it does this?

Name: Anonymous 2006-04-29 11:03

The first parameter to socket() is the _protocol_ family (well domain actually but that's basically the same thing these days), not the address family. For portable code, use PF_INET instead. AF_* is for the family field in a sockaddr subtype.

Also, why the hell are you casting length to an unsigned int pointer? Why not declare it to be the correct type in the first place?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List