async.c
资源名称:socks5.zip [点击查看]
上传用户:sddyfurun
上传日期:2007-01-04
资源大小:525k
文件大小:3k
源码类别:
代理服务器
开发平台:
Unix_Linux
- /* This code was written by Carson Gaspar, I've put it here just in case */
- /* anyone else has problems with non-blocking code... */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <fcntl.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <sys/time.h>
- #include <string.h>
- int main(int argc, char **argv)
- {
- int mysock,status,numfds;
- short port;
- struct hostent *hent;
- struct sockaddr_in mysa;
- fd_set rfds,wfds,efds;
- struct timeval mytv;
- if (argc != 3) {
- fprintf(stderr, "Usage: %s hostname portn", argv[0]);
- exit(255);
- }
- while ((hent = gethostbyname(argv[1])) == NULL) {
- switch(h_errno) {
- case HOST_NOT_FOUND:
- case NO_RECOVERY:
- case NO_DATA:
- fprintf(stderr,"Host %s not foundn", argv[1]);
- exit(255);
- break;
- case TRY_AGAIN:
- fprintf(stderr,"Failed to get address of %s, retryingn", argv[1]);
- break;
- }
- }
- if ((mysock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
- perror("socket failed");
- exit(255);
- }
- if (fcntl(mysock, F_SETFL, O_NONBLOCK)) {
- perror("fcntl F_SETFL O_NONBLOCK failed");
- exit(255);
- }
- mysa.sin_family = AF_INET;
- memcpy(&mysa.sin_addr, hent->h_addr, hent->h_length);
- errno = 0;
- port = (short) strtol(argv[2], NULL, 10);
- if (errno != 0) {
- perror("invalid port");
- exit(255);
- }
- mysa.sin_port = htons(port);
- status = 0;
- if ((connect(mysock,(struct sockaddr *) &mysa, sizeof(mysa))) < 0) {
- if ((errno != EALREADY) && (errno != EINPROGRESS)) {
- perror("connect failed");
- exit(255);
- } else {
- status = 1;
- perror("connect status");
- }
- } else {
- fprintf(stderr, "connection succeeded!n");
- exit(0);
- }
- while(status < 2) {
- FD_ZERO(&rfds);
- FD_ZERO(&wfds);
- FD_ZERO(&efds);
- FD_SET(mysock, &wfds);
- mytv.tv_sec = 2;
- mytv.tv_usec = 0;
- while ((numfds = select(FD_SETSIZE - 1, &rfds, &wfds, &efds, &mytv)) < 0) {
- if (errno != EINTR) {
- perror("select failed");
- exit(255);
- }
- }
- if (numfds == 0) {
- fprintf(stderr, "select returned with no fdsn");
- } else {
- if (FD_ISSET(mysock, &wfds)) {
- fprintf(stderr, "select returned socket writeble - trying to connectn");
- if ((connect(mysock,(struct sockaddr *) &mysa, sizeof(mysa))) < 0) {
- switch (errno) {
- case EALREADY:
- case EINPROGRESS:
- status = 1;
- perror("connect status");
- break;
- case EISCONN:
- fprintf(stderr, "connection succeeded!n");
- exit(0);
- break;
- default:
- perror("connect failed");
- exit(255);
- }
- } else {
- fprintf(stderr, "connection succeeded!n");
- exit(0);
- }
- }
- }
- }
- /* we should never get here */
- exit(1);
- }