45#include <netinet/in.h>
46#include <sys/socket.h>
48#include "utilities/qio.h"
49#include "utilities/qstring.h"
50#include "utilities/qsocket.h"
67 struct sockaddr_in addr;
74 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
79 int flags = fcntl(sockfd, F_GETFL, 0);
81 fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
84 int status = connect(sockfd, (
struct sockaddr *) &addr,
sizeof(addr));
86 && (errno != EINPROGRESS
94 fcntl(sockfd, F_SETFL, flags);
111 if (timeoutms >= 0 && shutdown(sockfd, SHUT_WR) == 0) {
114 ssize_t read =
qio_read(sockfd, buf,
sizeof(buf), timeoutms);
115 DEBUG(
"Throw %zu bytes from dummy input stream.", read);
121 if (close(sockfd) == 0)
137 memset((
void *) addr, 0,
sizeof(
struct sockaddr_in));
138 if (!inet_aton(hostname, &addr->sin_addr)) {
140 if ((hp = gethostbyname(hostname)) == 0)
142 memcpy(&addr->sin_addr, hp->h_addr,
sizeof(
struct in_addr));
144 addr->sin_family = AF_INET;
145 addr->sin_port = htons(port);
157 char hostname[63 + 1];
158 if (gethostname(hostname,
sizeof(hostname)) != 0)
161 struct hostent *hostentry = gethostbyname(hostname);
162 if (hostentry == NULL)
165 char *localip = inet_ntoa(*(
struct in_addr *) *hostentry->h_addr_list);
169 qstrcpy(buf, bufsize, localip);
ssize_t qio_read(int fd, void *buf, size_t nbytes, int timeoutms)
Read from a file descriptor.
int qio_wait_writable(int fd, int timeoutms)
Test & wait until the file descriptor is ready for writing.
bool qsocket_get_addr(struct sockaddr_in *addr, const char *hostname, int port)
Convert hostname to sockaddr_in structure.
bool qsocket_close(int sockfd, int timeoutms)
Close socket.
int qsocket_open(const char *hostname, int port, int timeoutms)
Create a TCP socket for the remote host and port.
char * qsocket_get_localaddr(char *buf, size_t bufsize)
Return local IP address.
char * qstrcpy(char *dst, size_t size, const char *src)
Copy src string to dst.