用C自己编写端口扫描软件.docx
- 文档编号:28239679
- 上传时间:2023-07-09
- 格式:DOCX
- 页数:7
- 大小:17.60KB
用C自己编写端口扫描软件.docx
《用C自己编写端口扫描软件.docx》由会员分享,可在线阅读,更多相关《用C自己编写端口扫描软件.docx(7页珍藏版)》请在冰豆网上搜索。
用C自己编写端口扫描软件
用C自己编写端口扫描软件
WriteyourownportscanningsoftwareinC
Thereisalotofcodeforportscanningsoftwareontheweb,butitdoesn'thavetobesuitablefortheunderpoweredbirdbirds.Ormostofthecodeareverylongandusethemultithreading(manyconceptsinrespecttomultithreadingisdisturbingenough,scanningpartiscalculated),keptmewaitingbothside;Eitherthespeedisslowandthelearningisnotuseful.TodayI'dliketotalkabouttheportscanningsoftwarethatIwroteafterlearningwinsock.
Portscanningsoftwarebasictrainofthoughtisnottosay,thereisnothingdifficultalgorithm,wethinkyoushouldknow,aslongastheendfromthestartingporttoporttraversal,itisfounditisoktoopentheportoutput.Ingeneral,thislookslikethis:
for(CurrPort=StartPort;CurrPort<=EndPort;currport+){scanexecution;}.Thesoftwaredoesn'tusemultithreadedtechnology,andyoudon'thavetoworryabouttheideaofmultithreading.Sowefromtwoaspectstodiscussthescanningsoftware,thefirstishowtoopentheportcanbefoundontheonehand,thesecondaspectishowtoimprovethescanningspeedoftheport.
Findtheopenport
Beforeweshowyouhowtofindopenports,let'sfirstrecognizeafunctioncalledconnect().TheconnectfunctionconnectsaflowsockettothespecifiedportofthespecifiedIPaddress.Theuseoftheconnectfunction:
intconnect(SOCKETs,conststructsockaddrFAR*name,intnamelen);Sparameterspecifiesthesocketusedtoconnectwords,thenameparameterpointstoasockaddr_instructurethatisusedtospecifytoconnecttotheserver'sIPaddressandport,namelenparameterspecifiesthelengthofthesockaddr_instructure.Whenthisparameterconnectionissuccessful,thefunctionreturns0,otherwisethereturnvalueisSOCKET_ERROR.Sothat'swhatwe'retalkingaboutintermsoftheuseoftheconnectfunction.Soyoushouldthinkaboutthat,right?
Weusethereturnvalueoftheconnectfunctiontofindtheopenportnumber.Well,lookatthedetailedcodeandhavedetailedcomments,ifyoudon'tunderstandthefunction,youcangotoMSDNoronline.
Intscan(char*Ip,intStartPort,intEndPort)
{
Clock_tStartTime,EndTime;//thestartandendofthescan
FloatCostTime;//thetimespentinthescanningprocess
WSADATAwsa.
TheSOCKETs.
Structsockaddr_inserver;
IntCurrPort;//currentport
Intret.
MAKEWORD(2,2),&wsa);//beforeyouusethewinsockfunction,youmustloadandinitializethedynamicconnectionlibrarywiththeWSAStartupfunction
Server.Thesin_family=AF_INET;//specifytheaddressformatandonlyAF_INETinwinsock
Server.sin_add.s_addr=inet_addr(Ip);//specifytheIPaddressscanned
StartTime=clock();
For(CurrPort=StartPort;CurrPort<=EndPort;CurrPort++)
{
S=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//createasocket
/*
SOCKETSOCKET(intaf,inttype,intprotocol);
Createasocketforthecommunicationconnection
Afparameters:
specifyasocketaddressformatandonlyAF_INETinwinsock
Typeparameter:
sockettype,whichUSEStheSOCK_STREAM,flowsocket
Protocolparameters:
specifyprotocoltype,usingIPPROTO_TCP(whichistheTCPprotocol)inconjunctionwithtype.
*/
Server.sin_port=htons(CurrPort);//specifytheportnumberthatisscannedfortheIPaddress
Ret=connect(s,(structsockaddr);sizeof(server));//theconnection
If(0==ret)//determinewhethertheconnectionissuccessful
{
Printf("%s:
%d\n",Ip,CurrPort);
Closesocket(s);
}
}
EndTime=clock();
(1)CostTime=(float)(endtime-starttime)/CLOCKS_PER_SEC;
Printf("Costtime:
%fsecond\n",CostTime);//thetimespentintheoutputscan
WSACleanup();//releasethedynamicconnectionlibraryandreleasethecreatedsocket
Return1;
}
Throughtheif(0==ret)candeterminewhethertheconnectionissuccessful(sidedishspecialreminder:
thiswrite0==ret,judgingitwithret==0,thereisnodifference,justintheCprogramminglanguage"==(equal)"and"="(assignment)willbemixed,ifwritten0=ret,suchcomplains,itisagoodwriting).Ok,let'scallitinthemainfunctionandtryourscanningsoftware.Scanningthe10portsofthemachinetookmorethan10seconds,andifyouscanthehostonthenetwork,it'sslower!
Whyisitsoslow?
BecauseTCPconnectionsforuptothreetimestoshakehands,thatistosay,confirmtheconnectionwithpacketneedscertainround-triptime,whenthehostontheInternetconnection,connectionprocessoftentakesafewseconds.Thiskindofscanningspeedisreallyunacceptable!
Ok,solet'slookatthesecondaspectofwhatwe'retalkingabout,speedup.
Improvethespeedofscanningport
Withtheabovefoundation,let'stakealookatotheraspectsoftheweb!
Whenasocketiscreated,itdefaultstoablockingmode,butwinsockrecommendsthatprogrammersusenon-blockingmode.Therearetwofunctionsthatcanbeusedtochangetheschemaofasocket:
theioctlsocketfunctionandtheWSAAsyncSelectfunction.TheioctlsocketfunctioncontinuesfromtheBSDUNIXSocketspecification,anditsusageis:
Intioctlsocket(SOCKETs,longCMD,u_longFAR*argp)Theparametersspecifiesthesockethandlethatneedstobesetup,CMDforthecommandparameter,andargpisapointertoaparameterthatisusedbytheCMDcommand.WhentheCMDisdesignatedasFIONBIOfunctionisusedtochangethesocketmodel,theniftheargppointingtothevariableto1,thentheoperationmodeofthesocketissettoanon-blockingmode.Herewedon'tusetheWSAAsyncSelectfunction.Usetheselectfunctioncandetectmultiplesocketcanread,writeorerroroccurs,andcanspecifythedetectiontimeout,itsusageisasfollows:
Intselect(intNFDS,fd_setFAR*readfds,fd_setFAR*writefds,fd_setFAR*exceptfds,conststructtimevalFAR*timeout);ParametersNFDStoandBSDUNIXSocket,compatibilityandfunctionwillthisparameterisignored,thereadfds,writefds,exceptfdspointingtodifferentFD_SETstructurerespectively,usedtospecifytheneedtodetecttheSockethandles.Inourportscanningsoftware,needtoletwritefdsspecifiedsocketisready,becausethecallstheconnectfunctionnon-blockingmodesocketconnectionissuccessful,thesocketcanbeusedtosenddata.Withthisknowledge,youcanlookatthespecific,completecode.Similarly,ifyoudon'tknowanything,checkouttheInternetorMSDN.
#include
#include
#include
#pragmacomment(lib,"ws2_32")
Intscan(char*Ip,intStartPort,intEndPort);
int主要(int命令行参数个数,char**argv)
{
int受潮湿腐烂;
如果(命令行参数个数!
=4)
{
printf("用法:
%s\n",argv[0]);
退出
(1);
}
ret=扫描(argv[1],atoi(argv[2]),atoi(argv[3]));
如果(ret)
printf("扫描好的\n”);
返回0;
}
int扫描(charIp、intStartPort、intEndPort)
{
EndTimeclock_t开始时间;
浮动CostTime;
TIMEVAL超时;
FD_SET面具;
WSADATAwsa;
套接字;
结构指向sockaddr_in服务器;
intCurrPort;
int受潮湿腐烂;
无符号长模式=1;//ioctlsocket函数的最后一个参数
WSAStartup(MAKEWORD(2,2),wsa);
TimeOut.tv_sec=0;
超时。
tv_usec=50;//超时为50毫秒
FD_ZERO(面具);
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr(Ip);
开始时间=时钟();
(CurrPort=StartPort;CurrPort<=EndPort;CurrPort++)
{
s=插座(AF_INETSOCK_STREAMIPPROTO_TCP);
FD_SET(年代,面具);
ioctlsocket(sFIONBIO模式);//设置为非阻塞模式
server.sin_port=htons(CurrPort);
连接(s(structsockaddr*)及服务器sizeof(服务器);
ret=选择(0,NULL,面具,NULL,超时);//查询可写入状态
如果(0==ret||1==ret)
{
closesocket(年代);
}
其他的
{
printf("%s:
%d\n”,Ip,CurrPort);
closesocket(年代);
}
}
EndTime=时钟();
CostTime=(浮动)(EndTime-StartTime)/CLOCKS_PER_SEC;
printf("成本时间:
%f第二\n”,CostTime);
WSACleanup();
返回1;
}
好了,编译一下它,让我们看看它的扫描速度吧!
扫描了100个端口,才用了2秒钟,没有使用多线程技术,同样也可以让速度提高!
这个程序都使用了winsock2提供的函数,只要了解了网络相关方面的函数就完全可以掌握了。
希望会给大家带来提高了!
如果有什么不正确的地方请大家指出,同时如果大家有什么新的想法,也请大家共享出来。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 自己 编写 端口扫描 软件