summaryrefslogtreecommitdiff
path: root/pjlib/src/pj/addr_resolv_sock.c
diff options
context:
space:
mode:
Diffstat (limited to 'pjlib/src/pj/addr_resolv_sock.c')
-rw-r--r--pjlib/src/pj/addr_resolv_sock.c59
1 files changed, 58 insertions, 1 deletions
diff --git a/pjlib/src/pj/addr_resolv_sock.c b/pjlib/src/pj/addr_resolv_sock.c
index 9b9eb6dc..36c1c574 100644
--- a/pjlib/src/pj/addr_resolv_sock.c
+++ b/pjlib/src/pj/addr_resolv_sock.c
@@ -19,8 +19,8 @@
#include <pj/addr_resolv.h>
#include <pj/assert.h>
#include <pj/string.h>
-#include <pj/compat/socket.h>
#include <pj/errno.h>
+#include <pj/compat/socket.h>
PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *hostname, pj_hostent *phe)
@@ -49,3 +49,60 @@ PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *hostname, pj_hostent *phe)
return PJ_SUCCESS;
}
+/* Resolve the IP address of local machine */
+pj_status_t pj_gethostip(pj_in_addr *addr)
+{
+ const pj_str_t *hostname = pj_gethostname();
+ struct pj_hostent he;
+ pj_str_t cp;
+ pj_in_addr loopip;
+ pj_status_t status;
+
+ cp = pj_str("127.0.0.1");
+ loopip = pj_inet_addr(&cp);
+
+ /* Try with resolving local hostname first */
+ status = pj_gethostbyname(hostname, &he);
+ if (status == PJ_SUCCESS) {
+ *addr = *(pj_in_addr*)he.h_addr;
+ }
+
+
+ /* If we end up with 127.0.0.1, resolve the IP by getting the default
+ * interface to connect to some public host.
+ */
+ if (status != PJ_SUCCESS || addr->s_addr == loopip.s_addr) {
+ pj_sock_t fd;
+ pj_sockaddr_in a;
+ int len;
+
+ status = pj_sock_socket(PJ_AF_INET, PJ_SOCK_DGRAM, 0, &fd);
+ if (status != PJ_SUCCESS) {
+ return status;
+ }
+
+ cp = pj_str("1.1.1.1");
+ pj_sockaddr_in_init(&a, &cp, 53);
+
+ status = pj_sock_connect(fd, &a, sizeof(a));
+ if (status != PJ_SUCCESS) {
+ pj_sock_close(fd);
+ return status;
+ }
+
+ len = sizeof(a);
+ status = pj_sock_getsockname(fd, &a, &len);
+ if (status != PJ_SUCCESS) {
+ pj_sock_close(fd);
+ return status;
+ }
+
+ pj_sock_close(fd);
+
+ *addr = a.sin_addr;
+ }
+
+ return status;
+}
+
+