1 /* $Id: upnputils.c,v 1.1 2013/09/07 06:45:39 nanard Exp $ */
2 /* MiniUPnP project
3 * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
4 * (c) 2006-2013 Thomas Bernard
5 * This software is subject to the conditions detailed
6 * in the LICENCE file provided within the distribution */
7
8 #include "config.h"
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <syslog.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <netinet/in.h>
18 #include <arpa/inet.h>
19 #ifdef AF_LINK
20 #include <net/if_dl.h>
21 #endif
22
23 #include "upnputils.h"
24
25 int
sockaddr_to_string(const struct sockaddr * addr,char * str,size_t size)26 sockaddr_to_string(const struct sockaddr * addr, char * str, size_t size)
27 {
28 char buffer[64];
29 unsigned short port = 0;
30 int n = -1;
31
32 switch(addr->sa_family)
33 {
34 case AF_INET6:
35 inet_ntop(addr->sa_family,
36 &((struct sockaddr_in6 *)addr)->sin6_addr,
37 buffer, sizeof(buffer));
38 port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
39 n = snprintf(str, size, "[%s]:%hu", buffer, port);
40 break;
41 case AF_INET:
42 inet_ntop(addr->sa_family,
43 &((struct sockaddr_in *)addr)->sin_addr,
44 buffer, sizeof(buffer));
45 port = ntohs(((struct sockaddr_in *)addr)->sin_port);
46 n = snprintf(str, size, "%s:%hu", buffer, port);
47 break;
48 #ifdef AF_LINK
49 #if defined(__sun)
50 /* solaris does not seem to have link_ntoa */
51 /* #define link_ntoa _link_ntoa */
52 #define link_ntoa(x) "dummy-link_ntoa"
53 #endif
54 case AF_LINK:
55 {
56 struct sockaddr_dl * sdl = (struct sockaddr_dl *)addr;
57 n = snprintf(str, size, "index=%hu type=%d %s",
58 sdl->sdl_index, sdl->sdl_type,
59 link_ntoa(sdl));
60 }
61 break;
62 #endif
63 default:
64 n = snprintf(str, size, "unknown address family %d", addr->sa_family);
65 #if 0
66 n = snprintf(str, size, "unknown address family %d "
67 "%02x %02x %02x %02x %02x %02x %02x %02x",
68 addr->sa_family,
69 addr->sa_data[0], addr->sa_data[1], (unsigned)addr->sa_data[2], addr->sa_data[3],
70 addr->sa_data[4], addr->sa_data[5], (unsigned)addr->sa_data[6], addr->sa_data[7]);
71 #endif
72 }
73 return n;
74 }
75
76
77 int
set_non_blocking(int fd)78 set_non_blocking(int fd)
79 {
80 int flags = fcntl(fd, F_GETFL);
81 if(flags < 0)
82 return 0;
83 if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
84 return 0;
85 return 1;
86 }
87
88