若需要使用的端口号被其它无用进程使用,可以用下面的方法将被占用的端口关闭
int closeSockFd(int port)
{
struct rlimit lim;
unsigned int i,val,exit=0;
int pock;
string spock;
struct sockaddr_in serv,guest;
socklen_t serv_len = sizeof(serv);
struct stat buf;
if (getrlimit(RLIMIT_NOFILE, &lim) < 0)
{
return -1;
}
if (lim.rlim_cur == RLIM_INFINITY)
{
lim.rlim_cur = 1024;
}
for (i = 3; i < lim.rlim_cur; i++)
{
fstat(i,&buf);
if(S_ISSOCK(buf.st_mode))
{
getsockname(i,(struct sockaddr *)&serv, &serv_len);
pock = ntohs(serv.sin_port);
if(pock==port)
{
val=fcntl(i,F_GETFD);
val |=FD_CLOEXEC;
if (fcntl(i,F_SETFD,val)==-1 && errno != EBADF)
{
return false;
}
exit=1;
}
serv.sin_port=0;
}
}
if(exit==0)
{
return false;
}
return true;
}
阅读(1711) | 评论(0) | 转发(0) |