一直在windows下写代码,突然想学习Linux 编程 写个小代码玩玩。只扫80端口。非阻塞套接字。轻量级信号量控制扫描线程数量。
#include <iostream>
#include <pthread.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdint.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <semaphore.h>
using namespace std;
std::vector<std::string> ret_list;
pthread_mutex_t g_mutex;
sem_t g_sem;
void *scan_thread(void *arg)
{
in_addr_t net_ip = (in_addr_t)arg;
char* s_ip = strdup( inet_ntoa( *(in_addr*)&net_ip ) );
struct sockaddr_in addr = {0};
addr.sin_family=AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = net_ip;
int sockfd = 0;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("\nsocket creat error");
return NULL;
}
int flags = fcntl(sockfd,F_GETFL,0);
fcntl(sockfd,F_SETFL,flags|O_NONBLOCK);
int retcode = -1;
retcode = connect(sockfd , (struct sockaddr*)&addr, sizeof(addr));
if( retcode != -1 || errno != EINPROGRESS)
{
printf("\n %s connect error!",s_ip);
sem_post( &g_sem );
exit(0);
}
if ( retcode == -1 )
{
fd_set wset;
struct timeval tv;
int retval;
FD_ZERO(&wset);
FD_SET(sockfd, &wset);
tv.tv_sec = 2;
tv.tv_usec = 0;
retval = select(sockfd+1, NULL , &wset, NULL, &tv);
if ( retval <= 0 )
{
printf("\n %s time out connect error",s_ip);
close(sockfd);
free(s_ip);
sem_post( &g_sem );
return 0;
}
if ( !FD_ISSET(sockfd, &wset) )
{
printf("\n%s connect false!",s_ip);
close(sockfd);
free(s_ip);
return 0;
}
int err;
socklen_t len = sizeof(int);
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
{
close(sockfd);
free(s_ip);
sem_post( &g_sem );
return 0;
}
if (err != 0)
{
printf("\n%s connect false!",s_ip);
close(sockfd);
free(s_ip);
sem_post( &g_sem );
return 0;
}
printf("\n%s connect succuss!", s_ip );
close(sockfd);
pthread_mutex_lock( &g_mutex );
ret_list.push_back( s_ip );
pthread_mutex_unlock( &g_mutex );
}
free(s_ip);
sem_post( &g_sem );
return NULL;
}
int main(int argc , char* argv[] )
{
in_addr_t net_start = (in_addr_t)inet_addr(argv[1]);
in_addr_t net_end = (in_addr_t)inet_addr(argv[2]);
unsigned int i_start = ntohl( net_start );
unsigned int i_end = ntohl( net_end );
sem_init( &g_sem, 0, 20 );
pthread_mutex_init( &g_mutex, NULL );
while ( i_start <= i_end )
{
pthread_t tid = 0;
sem_wait( &g_sem );
if (pthread_create(&tid,NULL,scan_thread,(void*)htonl(i_start))!=0)
{
printf("\nCreate thread error!");
exit(1);
}
i_start++;
}
sleep(10);
printf("\nopen 80 have Num: %d\n",ret_list.size() );
std::vector<std::string>::iterator pos = ret_list.begin();
while ( pos != ret_list.end() )
{
printf("\n %s",pos->c_str());
pos++;
}
pthread_mutex_destroy( &g_mutex );
return 0;
}