生成随机端口函数

这个函数用来生成一个随机端口,可以生成一个没有被占用的端口。

//生成随机端口
DWORD GenerateRandomPort()
{
	int nStartPort = 1000;
	int nEndPort = 10000;
	FD_SET fd_Write;
	SOCKET s;
	struct sockaddr_in server;
	struct timeval tp = { 0 };
	int ret = 0;
	unsigned long mode = 1; 
	tp.tv_sec = 0;  
	tp.tv_usec = 50; 
	FD_ZERO(&fd_Write);  
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("127.0.0.1");
	for(nStartPort; nStartPort != nEndPort; ++nStartPort)
	{
		s=socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
		FD_SET(s, &fd_Write);
		ioctlsocket(s, FIONBIO, &mode); 
		server.sin_port=htons(nStartPort);
		connect(s,(struct sockaddr *)&server,sizeof(server));
		ret=select(0, NULL, &fd_Write, NULL, &tp);  
		if(0 == ret || -1 == ret)
		{
			closesocket(s);
			WSACleanup();
			return nStartPort;
		}
		closesocket(s);
	}
	WSACleanup();
	return nStartPort;
}

posted @ 2010-10-29 11:43  天堂大鸟  阅读(1598)  评论(3编辑  收藏  举报