- 爱易网页
-
Linux
- 小弟我在linux下写了个简单的多线程端口扫描程序,运行时出现有关问题,请问一下
日期:2014-05-16 浏览次数:20602 次
我在linux下写了个简单的多线程端口扫描程序,运行时出现问题,请教一下!
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <netinet/in.h>
struct sockaddr_in servaddr;
int g_nThreadNum, g_nMaxThread;
long g_nNowPort;
char *host;
struct timeval timeout;
static void* thread_scan_port(void *pPort)
{
int sockfd, flags, error,nPort, retconn, retval, len;
fd_set wfds;
pthread_detach(pthread_self());
nPort = *(int *)pPort;
//printf( "nPort = %d\n ", nPort);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror( "\nsocket ");
g_nThreadNum--;
return(NULL);
}
/* 设为非阻塞方式 */
if ((flags = fcntl(sockfd, F_GETFL, 0)) < 0)
{
perror( "\nfcntl: ");
g_nThreadNum--;
return(NULL);
}
if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0)
{
perror( "\nfcntl: ");
g_nThreadNum--;
return(NULL);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(nPort);
servaddr.sin_addr.s_addr = inet_addr(host);
if ((retconn = connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
if (EINPROGRESS != errno)
{
g_nThreadNum--;
return(NULL);
}
FD_ZERO(&wfds);
FD_SET(sockfd, &wfds);
retval = select(sockfd+1, NULL, &wfds, NULL, &timeout);
if (0 == retval || -1 == retval) /* 超时或者select错误 */
{
//printf( "port connect is fail!\n ");
close(sockfd);
g_nThreadNum--;
return(NULL);
}
if (FD_ISSET(sockfd, &wfds)) /* sockfd可写 */
{
len = sizeof(error);
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
{
g_nThreadNum--;
return(NULL);
}
}
else
{
perror( "\nFD_ISSET: ");
g_nThreadNum--;
return(NULL);
}
if (error) /* 链接时有错误发生 */
{
close(sockfd);
g_nThreadNum--;
return(NULL);
}
else /* 链接成功返回0 */
{
printf( "port %d is opened!\n ", nPort);
g_nThreadNum--;
return(NULL);
}