freeing port - winsock

J

Julien Ghaye

Hi everyone,

Actually, I'm coding some kind of a http client.

Here is my problem. When I create and destroy many sockets (one after
another) without specifying the local port to bind, It seems that this
local port is not free after using the function closesocket().

So, How can I free it ?

Here is a small programm that I code quickly. It's goal is to create a
socket, connect to a remote server on port 80, close the socket and to
loop on these actions.
It displays the local port in use.
You'll see that after having used the default range 1024-5000, you get a
10048 error (adresse in use)

Any ideas ?

Thanks all,
Julien


///////////////////// CODE ////////////////////


#include <iostream>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

using namespace std;

int host(SOCKET s, char* buff, int* length)
{
sockaddr name;
int namelen = sizeof(sockaddr);
if ((getsockname(s,&name,&namelen) == SOCKET_ERROR) ||
(WSAAddressToString(&name,namelen,NULL,buff,(LPDWORD)length) ==
SOCKET_ERROR))
{
cout << "An error Occurs .... error code : " <<
WSAGetLastError() << endl;
return -1;
}
return 0;
}


void main()
{
WSADATA WSAData;
SOCKET sock = INVALID_SOCKET;
SOCKADDR_IN sin;
int buff_len = 255;
char *buffer = new char[buff_len];

cout << "Stratup" << endl;
WSAStartup(MAKEWORD(2,0), &WSAData);
bool optVal = true;

while(true)
{
sock = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
cout << "Connecting " ;
if(connect(sock, (SOCKADDR *)&sin, sizeof(sin)) == SOCKET_ERROR)
{
cout << " ... Error : " << WSAGetLastError() << endl;
break;
}
//setsockopt(sock,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,(char
*)&optVal, sizeof(bool));
host (sock, buffer, &buff_len);
cout << "from" << buffer << "\r";
closesocket(sock);
sock = INVALID_SOCKET;
}
cout << "Cleaning up" << endl;
sock = INVALID_SOCKET;
WSACleanup();
cin >> new char;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top