1 /* Copyright (C) 2007 Board of Trustees, Leland Stanford Jr. University.
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to
5 * deal in the Software without restriction, including without limitation the
6 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 * sell copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 #include "socket-util.h"
23 #include <arpa/inet.h>
32 #define THIS_MODULE VLM_socket_util
34 /* Sets 'fd' to non-blocking mode. Returns 0 if successful, otherwise a
35 * positive errno value. */
37 set_nonblocking(int fd)
39 int flags = fcntl(fd, F_GETFL, 0);
41 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
44 VLOG_ERR("fcntl(F_SETFL) failed: %s", strerror(errno));
48 VLOG_ERR("fcntl(F_GETFL) failed: %s", strerror(errno));
53 /* Translates 'host_name', which may be a DNS name or an IP address, into a
54 * numeric IP address in '*addr'. Returns 0 if successful, otherwise a
55 * positive errno value. */
57 lookup_ip(const char *host_name, struct in_addr *addr)
59 if (!inet_aton(host_name, addr)) {
60 struct hostent *he = gethostbyname(host_name);
62 VLOG_ERR("gethostbyname(%s): %s", host_name,
63 (h_errno == HOST_NOT_FOUND ? "host not found"
64 : h_errno == TRY_AGAIN ? "try again"
65 : h_errno == NO_RECOVERY ? "non-recoverable error"
66 : h_errno == NO_ADDRESS ? "no address"
70 addr->s_addr = *(uint32_t *) he->h_addr;
75 /* Returns the error condition associated with socket 'fd' and resets the
76 * socket's error status. */
78 get_socket_error(int fd)
81 socklen_t len = sizeof(error);
82 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
84 VLOG_ERR("getsockopt(SO_ERROR): %s", strerror(error));
90 check_connection_completion(int fd)
98 retval = poll(&pfd, 1, 0);
99 } while (retval < 0 && errno == EINTR);
101 return get_socket_error(fd);
102 } else if (retval < 0) {
103 VLOG_ERR("poll: %s", strerror(errno));