Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/select.h>
- #include <errno.h>
- #include <inttypes.h>
- void error(char *msg)
- {
- perror(msg);
- exit(1);
- }
- char* scan(int begin, int end, char* ip, int timeout)
- {
- int socketfd, retval;
- fd_set rfds;
- //set timeout
- struct timeval tv;
- tv.tv_sec = 0;
- //create address
- struct sockaddr_in address;
- //zero address memory
- memset(&address,0, sizeof(address));
- //initialize address
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = inet_addr(ip);
- if (address.sin_addr.s_addr == -1)
- error("Invalid IP address format");
- int port;
- for (port = begin; port <= end; ++port)
- {
- //set port in network bit order
- address.sin_port = htons(port);
- //get socket file descriptor
- socketfd = socket(AF_INET, SOCK_STREAM, 0);
- if (socketfd < 0)
- error("ERROR opening socket");
- //add socket descriptor to set
- FD_ZERO(&rfds);
- FD_SET(socketfd, &rfds);
- //make socket non-blocking
- int flags = fcntl(socketfd, F_GETFL, 0);
- fcntl(socketfd, F_SETFL, flags | O_NONBLOCK);
- //try to connect
- retval = connect(socketfd,(struct sockaddr *)&address,sizeof(address));
- //on failure to connect
- if (retval == -1)
- {
- //if connection is waiting
- if (errno == EINPROGRESS)
- {
- //reset timeout value
- tv.tv_usec = timeout;
- //wait until descriptor in set becomes writable, or operation times out
- retval = select(socketfd+1,NULL,&rfds,NULL,&tv);
- if (retval == -1)
- {
- error("select() failed");
- }
- else if (retval)
- {
- //check if something went wrong
- int optval, len;
- getsockopt(socketfd,SOL_SOCKET,SO_ERROR,&optval,&len);
- //print appropriate message
- if (optval)
- {
- if (optval == ECONNREFUSED)
- printf("%d::closed\n",port);
- else
- {
- printf("Error value:%d %d::error\n",optval,port);
- }
- }
- else
- printf("%d::open\n",port);
- }
- else
- {
- printf("%d::timed out\n",port);
- }
- }
- }
- close(socketfd);
- }
- return NULL;
- }
- int main(int argc, char* argv[])
- {
- int begin, end, timeout;
- char ip[16];
- int i;
- for (i = 0; i < argc; ++i)
- {
- //if argument starts with '-'
- if (argv[i][0] == '-')
- {
- switch (argv[i][1])
- {
- case 'a':
- {
- strncpy(ip,argv[++i],15);
- break;
- }
- case 'b':
- {
- begin = atoi(argv[++i]);
- break;
- }
- case 'e':
- {
- end = atoi(argv[++i]);
- break;
- }
- case 't':
- {
- timeout = atoi(argv[++i]);
- break;
- }
- default:
- {
- error("Invalid argument");
- }
- };
- }
- }
- //printf("begin: %d\nend: %d\naddress: %s\ntimeout: %d\n",begin,end,ip,timeout);
- char* result = scan(begin,end,ip,timeout);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement