#include #include #include #include #include #include #include int main(int argc, char **argv){ char hostname[255]; char buffy[512]; int port; int s; int status; int flags; struct hostent *he; struct sockaddr_in address; struct timeval timeout; fd_set timeout_sockets; fd_set read_sockets; extern int h_errno; timeout.tv_sec = 20; timeout.tv_usec = 0; if (argc != 3){ printf("USAGE: %s \n", argv[0]); exit(0); } s = socket(AF_INET, SOCK_STREAM, 0); if (!s){ perror("Create socket"); exit(0); } strncpy(hostname, argv[1], 255); port = atoi(argv[2]); if ((he = gethostbyname(hostname)) == NULL){ herror("gethostbyname"); close(s); exit(0); } memcpy(&address.sin_addr, he->h_addr_list[0], he->h_length); address.sin_family = AF_INET; address.sin_port = htons(port); FD_ZERO(&timeout_sockets); FD_SET(0, &timeout_sockets); flags = fcntl(s, F_GETFL, 0); fcntl(s, F_SETFL, flags | O_NONBLOCK); printf("Connecting to %s:%d ...\n", hostname, port); connect(s, (struct sockaddr *) &address, sizeof(address)); status = select(s + 1, NULL, &timeout_sockets, NULL, &timeout); if (status == 1) printf("Connected to %s:%d\n", hostname, port); else if ((recv(s, NULL, 1, 0)) < 0){ perror("Could not connect"); close(s); exit(0); } FD_ZERO(&read_sockets); FD_SET(s, &read_sockets); status = select(s+1, &read_sockets, NULL, NULL, &timeout); if (status){ recv(s, buffy, sizeof(buffy), 0); printf("RECV_BUFFER: %s\n", buffy); } close(s); }