3397fdb3999d83ce6b2e94ffdc45a9aa2308c395
[openvswitch] / lib / socket-util.c
1 /* Copyright (C) 2007 Board of Trustees, Leland Stanford Jr. University.
2  *
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:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
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
19  * IN THE SOFTWARE.
20  */
21
22 #include "socket-util.h"
23 #include <arpa/inet.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <netdb.h>
27 #include <stdio.h>
28
29 #include "vlog.h"
30 #define THIS_MODULE VLM_socket_util
31
32 /* Sets 'fd' to non-blocking mode.  Returns 0 if successful, otherwise a
33  * positive errno value. */
34 int
35 set_nonblocking(int fd)
36 {
37     int flags = fcntl(fd, F_GETFL, 0);
38     if (flags != -1) {
39         return fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1 ? 0 : errno;
40     } else {
41         return errno;
42     }
43 }
44
45 /* Translates 'host_name', which may be a DNS name or an IP address, into a
46  * numeric IP address in '*addr'.  Returns 0 if successful, otherwise a
47  * positive errno value. */
48 int
49 lookup_ip(const char *host_name, struct in_addr *addr) 
50 {
51     if (!inet_aton(host_name, addr)) {
52         struct hostent *he = gethostbyname(host_name);
53         if (he == NULL) {
54             VLOG_ERR("gethostbyname(%s): %s", host_name,
55                      (h_errno == HOST_NOT_FOUND ? "host not found"
56                       : h_errno == TRY_AGAIN ? "try again"
57                       : h_errno == NO_RECOVERY ? "non-recoverable error"
58                       : h_errno == NO_ADDRESS ? "no address"
59                       : "unknown error"));
60             return ENOENT;
61         }
62         addr->s_addr = *(uint32_t *) he->h_addr;
63     }
64     return 0;
65 }