Ticket #2963: nonblock-connect-test.cpp

File nonblock-connect-test.cpp, 1.7 KB (added by bonefish, 15 years ago)
Line 
1/*
2 * Copyright 2008, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
5
6#include <errno.h>
7#include <fcntl.h>
8#include <netinet/in.h>
9#include <stdint.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13#include <unistd.h>
14#include <sys/socket.h>
15#include <sys/time.h>
16
17
18#ifdef __HAIKU__
19# include <OS.h>
20#else
21
22typedef int64_t bigtime_t;
23
24static bigtime_t
25system_time()
26{
27 timeval tv;
28 gettimeofday(&tv, NULL);
29 return (bigtime_t)tv.tv_sec * 1000000 + tv.tv_usec;
30}
31
32
33#endif // !__HAIKU__
34
35
36int
37main(int argc, const char* const* argv)
38{
39 // create socket
40 int fd = socket(AF_INET, SOCK_STREAM, 0);
41 if (fd < 0) {
42 fprintf(stderr, "failed to create socket: %s\n", strerror(errno));
43 exit(1);
44 }
45
46 // set to non-blocking
47 int flags = fcntl(fd, F_GETFL);
48 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
49 fprintf(stderr, "failed to set to non-blocking: %s\n",
50 strerror(errno));
51 exit(1);
52 }
53
54 bigtime_t startTime = system_time();
55
56 // connect it
57 sockaddr_in addr;
58 addr.sin_family = AF_INET;
59 addr.sin_addr.s_addr = htonl(0x4a7d2768);
60 addr.sin_port = htons(80);
61 socklen_t addrLen = sizeof(addr);
62 if (connect(fd, (sockaddr*)&addr, addrLen) < 0) {
63 if (errno != EINPROGRESS) {
64 fprintf(stderr, "failed to connect(): %s\n", strerror(errno));
65 exit(1);
66 }
67 }
68
69 // wait for the connection to be established
70 fd_set writeSet;
71 FD_ZERO(&writeSet);
72 FD_SET(fd, &writeSet);
73
74 int result = select(fd + 1, NULL, &writeSet, NULL, NULL);
75 bigtime_t endTime = system_time();
76 if (result != 1)
77 fprintf(stderr, "select() unexpectedly returned: %d\n", result);
78
79 printf("Connection took %llu us\n", endTime - startTime);
80
81 return 0;
82}
83