linux下的connect端口扫描程序

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
int main(int argc,char *argv[])
{
	if(argc!=4)
	{
			printf("please input %s <host> <start> and <end> port\n",argv[0]);
			return 0;
	}
	
	int sport=atoi(argv[2]),eport=atoi(argv[3]);

	int sockfd,num;
	struct hostent *he;
	struct sockaddr_in server;
	struct servent *sp;
	if((he=gethostbyname(argv[1]))==NULL)
	{
			printf("gethostbyname error\n");
			return 0;
	}

	for(int i=sport;i<=eport;i++)
	{

			if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
			{
				printf("socket() error\n");
				return 0;
			}
			bzero(&server,sizeof(server));
			server.sin_family = AF_INET;
			server.sin_port = htons(i);
			server.sin_addr.s_addr = inet_addr(argv[1]);
			if(connect(sockfd,(struct sockaddr*)&server,sizeof(server))==-1)
			{
				close(sockfd);
			}
			else
			{
				sp=getservbyport(server.sin_port,"tcp");
				
				printf("Port %d is open.%s\n",i,(sp==NULL)?"unknow ":sp->s_name);
			}
			close(sockfd);
	}
	return 1;
}

仅对同一网段内的主机有效。

linux下的connect端口扫描程序_第1张图片



你可能感兴趣的:(linux,server,socket,Stream,struct,null)