Parker Schuh | b59bf5e | 2016-12-28 21:09:36 -0800 | [diff] [blame] | 1 | #include "aos/vision/events/tcp_client.h" |
| 2 | |
| 3 | #include <arpa/inet.h> |
| 4 | #include <errno.h> |
| 5 | #include <fcntl.h> |
| 6 | #include <netdb.h> |
| 7 | #include <netinet/in.h> |
| 8 | #include <stdio.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <string.h> |
| 11 | #include <sys/socket.h> |
| 12 | #include <sys/types.h> |
| 13 | #include <unistd.h> |
| 14 | #include <unistd.h> |
| 15 | |
| 16 | #include "aos/common/logging/logging.h" |
| 17 | |
| 18 | namespace aos { |
| 19 | namespace events { |
| 20 | |
| 21 | namespace { |
| 22 | int MakeSocketNonBlocking(int sfd) { |
| 23 | int flags; |
| 24 | |
| 25 | PCHECK(flags = fcntl(sfd, F_GETFL, 0)); |
| 26 | |
| 27 | flags |= O_NONBLOCK; |
| 28 | PCHECK(fcntl(sfd, F_SETFL, flags)); |
| 29 | |
| 30 | return 0; |
| 31 | } |
| 32 | |
Parker Schuh | 309dd72 | 2017-02-25 11:31:18 -0800 | [diff] [blame] | 33 | int OpenClient(const std::string &hostname, int portno) { |
Parker Schuh | b59bf5e | 2016-12-28 21:09:36 -0800 | [diff] [blame] | 34 | int sockfd; |
| 35 | struct sockaddr_in serveraddr; |
| 36 | struct hostent *server; |
| 37 | /* socket: create the socket */ |
| 38 | PCHECK(sockfd = socket(AF_INET, SOCK_STREAM, 0)); |
| 39 | |
| 40 | /* gethostbyname: get the server's DNS entry */ |
Parker Schuh | 309dd72 | 2017-02-25 11:31:18 -0800 | [diff] [blame] | 41 | server = gethostbyname(hostname.c_str()); |
Parker Schuh | b59bf5e | 2016-12-28 21:09:36 -0800 | [diff] [blame] | 42 | if (server == NULL) { |
Parker Schuh | 309dd72 | 2017-02-25 11:31:18 -0800 | [diff] [blame] | 43 | fprintf(stderr, "ERROR, no such host as %s\n", hostname.c_str()); |
Parker Schuh | b59bf5e | 2016-12-28 21:09:36 -0800 | [diff] [blame] | 44 | exit(-1); |
| 45 | } |
| 46 | |
| 47 | /* build the server's Internet address */ |
| 48 | bzero((char *)&serveraddr, sizeof(serveraddr)); |
| 49 | serveraddr.sin_family = AF_INET; |
| 50 | bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, |
| 51 | server->h_length); |
| 52 | serveraddr.sin_port = htons(portno); |
| 53 | |
| 54 | /* connect: create a connection with the server */ |
| 55 | PCHECK(connect(sockfd, (const struct sockaddr *)&serveraddr, |
| 56 | sizeof(serveraddr))); |
| 57 | PCHECK(MakeSocketNonBlocking(sockfd)); |
| 58 | |
| 59 | return sockfd; |
| 60 | } |
| 61 | } // namespace |
| 62 | |
Parker Schuh | 309dd72 | 2017-02-25 11:31:18 -0800 | [diff] [blame] | 63 | TcpClient::TcpClient(const std::string &hostname, int portno) |
Parker Schuh | b59bf5e | 2016-12-28 21:09:36 -0800 | [diff] [blame] | 64 | : EpollEvent(OpenClient(hostname, portno)) {} |
| 65 | |
| 66 | } // namespace events |
| 67 | } // namespace aos |