- //TcpPortScanner.cc
- #include <iostream>
- #include <strings.h>
- #include <stdlib.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- using namespace std;
- int main(int argc, char *argv[])
- {
- int fromport = atoi(argv[2]);
- int toport = atoi(argv[3]);
- if(fromport > toport)
- {
- int temp;
- temp = fromport;
- fromport = toport;
- toport = temp;
- }
- for(int i = fromport; i < toport; i++)
- {
- int sk = socket(AF_INET, SOCK_STREAM, 0);
- struct sockaddr_in server;
- 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(sk, (struct sockaddr*)&server, sizeof(server)) == 0)
- {
- cout << argv[1] << "开放了端口:" << i << endl;
- }
- close(sk);
- }
- return 0;
- }
套接字socket(即sk)要在for循环里面创建,如果在for循环外面创建则第一次connect函数成功之后,sk并没有关闭,不能用来连接其他的端口,则下次的connect连接就会失败,所有只会扫描出一个开了的端口。