Parker Kemp
Parker Kemp

Reputation: 765

Socket bound on one port, but tools like netstat and lsof show it listening on some other port

The relevant code is below. I bind the socket on port 12345, and the code works completely as expected. It responds to requests on that port and everything.

However, tools such as netstat or lsof are showing the process listening on port 14640, almost invariably. I was perplexed at this, and I finally decided to see what would happen if I instead bound the socket on port 14640. Well it turns out that when it's bound on 14640, lsof shows it listening on (I shit you not) the original port, 12345. I went back and forth and kept seeing the same results going both ways. It's as if these two numbers have some weird relationship with each other.

Am I losing my mind? Is there an explanation for this behavior?

SOCKET sock, clientSock;
sockaddr_in serverAddress, clientAddress;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
    printff("Error opening socket\n");
    return;
}

char *temp = (char *)&serverAddress;
for (int i = 0; i < sizeof(serverAddress); i++) {
    temp[i] = 0;
}

serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = port; //port = 12345

int b = bind(sock, (sockaddr*)&serverAddress, sizeof(serverAddress));
if (b != 0) {
    printff("Unable to bind: %i\n", lastError());
    return;
}

int res = listen(sock, SOMAXCONN);
if (res != 0) {
    printff("Unable to listen: %i\n", lastError());
    return;
}

socklen_t clilen = sizeof(*clientAddress);
clientSock = accept(sock, (sockaddr*)&clientAddress, &clilen);

Upvotes: 0

Views: 181

Answers (1)

user207421
user207421

Reputation: 310850

serverAddress.sin_port = port; //port = 12345

That should be

serverAddress.sin_port = htons(port); //port = 12345

as shown in practically any example anywhere.

It's as if these two numbers have some weird relationship with each other.

They do. One is the byte-swapped value of the other. 0x3039 and 0x3930.

Upvotes: 2

Related Questions