By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,336 Members | 2,315 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,336 IT Pros & Developers. It's quick & easy.

freeing port - winsock

P: n/a
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,(LPDWO RD)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,(ch ar
*)&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;
}
Aug 9 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.