]>
git.saurik.com Git - wxWidgets.git/blob - src/common/sckaddr.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/sckaddr.cpp
3 // Purpose: Network address manager
4 // Author: Guilhem Lavaux
6 // Modified by: Vadim Zeitlin to use wxSockAddressImpl on 2008-12-28
8 // Copyright: (c) 1997, 1998 Guilhem Lavaux
9 // (c) 2008 Vadim Zeitlin
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // ============================================================================
15 // ============================================================================
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
31 #include "wx/object.h"
34 #include "wx/thread.h"
40 #if !defined(__MWERKS__)
45 #include "wx/socket.h"
46 #include "wx/sckaddr.h"
47 #include "wx/private/socket.h"
48 #include "wx/private/sckaddr.h"
54 #include <arpa/inet.h>
58 #define INADDR_NONE INADDR_ANY
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
65 IMPLEMENT_ABSTRACT_CLASS(wxSockAddress
, wxObject
)
66 IMPLEMENT_ABSTRACT_CLASS(wxIPaddress
, wxSockAddress
)
67 IMPLEMENT_DYNAMIC_CLASS(wxIPV4address
, wxIPaddress
)
69 IMPLEMENT_DYNAMIC_CLASS(wxIPV6address
, wxIPaddress
)
71 #if defined(__UNIX__) && !defined(__WINDOWS__) && !defined(__WINE__)
72 IMPLEMENT_DYNAMIC_CLASS(wxUNIXaddress
, wxSockAddress
)
75 // ============================================================================
76 // implementation of thread-safe/reentrant functions if they're missing
77 // ============================================================================
79 // TODO: use POSIX getaddrinfo() (also available in Winsock 2) for simplicity
80 // and to use the same code for IPv4 and IPv6 support
83 #define HAVE_INET_ADDR
85 #define HAVE_GETHOSTBYNAME
86 #define HAVE_GETSERVBYNAME
88 // under MSW getxxxbyname() functions are MT-safe (but not reentrant) so
89 // we don't need to serialize calls to them
90 #define wxHAS_MT_SAFE_GETBY_FUNCS
93 // this header does dynamic dispatching of getaddrinfo/freeaddrinfo()
94 // by implementing them in its own code if the system versions are not
95 // available (as is the case for anything < XP)
97 // NB: if this is not available for the other compilers (so far tested
98 // with MSVC only) we should just use wxDynamicLibrary "manually"
100 // disable a warning occurring in Microsoft own version of this file
101 #pragma warning(disable:4706)
105 #pragma warning(default:4706)
110 // we assume that we have gethostbyaddr_r() if and only if we have
111 // gethostbyname_r() and that it uses the similar conventions to it (see
112 // comment in configure)
113 #define HAVE_GETHOSTBYADDR HAVE_GETHOSTBYNAME
114 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
115 #define HAVE_FUNC_GETHOSTBYADDR_R_3
117 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_5
118 #define HAVE_FUNC_GETHOSTBYADDR_R_5
120 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_6
121 #define HAVE_FUNC_GETHOSTBYADDR_R_6
124 // the _r functions need the extra buffer parameter but unfortunately its type
125 // differs between different systems and for the systems which use opaque
126 // structs for it (at least AIX and OpenBSD) it must be zero-filled before
127 // being passed to the system functions
128 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
129 struct wxGethostBuf
: hostent_data
133 memset(this, 0, sizeof(hostent_data
));
137 typedef char wxGethostBuf
[1024];
140 #ifdef HAVE_FUNC_GETSERVBYNAME_R_4
141 struct wxGetservBuf
: servent_data
145 memset(this, 0, sizeof(servent_data
));
149 typedef char wxGetservBuf
[1024];
152 #if defined(wxHAS_MT_SAFE_GETBY_FUNCS) || !wxUSE_THREADS
153 #define wxLOCK_GETBY_MUTEX(name)
154 #else // may need mutexes to protect getxxxbyxxx() calls
155 #if defined(HAVE_GETHOSTBYNAME) || \
156 defined(HAVE_GETHOSTBYADDR) || \
157 defined(HAVE_GETSERVBYNAME)
158 #include "wx/thread.h"
162 // these mutexes are used to serialize
163 wxMutex nameLock
, // gethostbyname()
164 addrLock
, // gethostbyaddr()
165 servLock
; // getservbyname()
168 #define wxLOCK_GETBY_MUTEX(name) wxMutexLocker locker(name ## Lock)
169 #endif // we don't have _r functions
170 #endif // wxUSE_THREADS
175 #if defined(HAVE_GETHOSTBYNAME)
176 hostent
*deepCopyHostent(hostent
*h
,
182 /* copy old structure */
183 memcpy(h
, he
, sizeof(hostent
));
186 int len
= strlen(h
->h_name
);
192 memcpy(buffer
, h
->h_name
, len
);
196 /* track position in the buffer */
199 /* reuse len to store address length */
202 /* ensure pointer alignment */
203 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
204 if(misalign
< sizeof(char *))
207 /* leave space for pointer list */
208 char **p
= h
->h_addr_list
, **q
;
209 char **h_addr_list
= (char **)(buffer
+ pos
);
211 pos
+= sizeof(char *);
213 /* copy addresses and fill new pointer list */
214 for (p
= h
->h_addr_list
, q
= h_addr_list
; *p
!= 0; p
++, q
++)
216 if (size
< pos
+ len
)
221 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
222 *q
= buffer
+ pos
; /* set copied pointer to copied content */
225 *++q
= 0; /* null terminate the pointer list */
226 h
->h_addr_list
= h_addr_list
; /* copy pointer to pointers */
228 /* ensure word alignment of pointers */
229 misalign
= sizeof(char *) - pos%sizeof
(char *);
230 if(misalign
< sizeof(char *))
233 /* leave space for pointer list */
235 char **h_aliases
= (char **)(buffer
+ pos
);
237 pos
+= sizeof(char *);
239 /* copy aliases and fill new pointer list */
240 for (p
= h
->h_aliases
, q
= h_aliases
; *p
!= 0; p
++, q
++)
243 if (size
<= pos
+ len
)
248 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
249 buffer
[pos
+ len
] = '\0';
250 *q
= buffer
+ pos
; /* set copied pointer to copied content */
253 *++q
= 0; /* null terminate the pointer list */
254 h
->h_aliases
= h_aliases
; /* copy pointer to pointers */
258 #endif // HAVE_GETHOSTBYNAME
260 hostent
*wxGethostbyname_r(const char *hostname
,
267 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
268 gethostbyname_r(hostname
, h
, buffer
, size
, &he
, err
);
269 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
270 he
= gethostbyname_r(hostname
, h
, buffer
, size
, err
);
271 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
272 he
= gethostbyname_r(hostname
, h
, &buffer
);
274 #elif defined(HAVE_GETHOSTBYNAME)
275 wxLOCK_GETBY_MUTEX(name
);
277 he
= gethostbyname(hostname
);
281 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
283 #error "No gethostbyname[_r]()"
289 hostent
*wxGethostbyaddr_r(const char *addr_buf
,
298 #if defined(HAVE_FUNC_GETHOSTBYADDR_R_6)
299 gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, &he
, err
);
300 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_5)
301 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, err
);
302 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_3)
303 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
);
305 #elif defined(HAVE_GETHOSTBYADDR)
306 wxLOCK_GETBY_MUTEX(addr
);
308 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
312 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
314 #error "No gethostbyaddr[_r]()"
320 #if defined(HAVE_GETSERVBYNAME)
321 servent
*deepCopyServent(servent
*s
,
326 /* copy plain old structure */
327 memcpy(s
, se
, sizeof(servent
));
330 int len
= strlen(s
->s_name
);
335 memcpy(buffer
, s
->s_name
, len
);
339 /* track position in the buffer */
343 len
= strlen(s
->s_proto
);
344 if (pos
+ len
>= size
)
348 memcpy(buffer
+ pos
, s
->s_proto
, len
);
349 buffer
[pos
+ len
] = '\0';
350 s
->s_proto
= buffer
+ pos
;
352 /* track position in the buffer */
355 /* ensure pointer alignment */
356 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
357 if(misalign
< sizeof(char *))
360 /* leave space for pointer list */
361 char **p
= s
->s_aliases
, **q
;
362 char **s_aliases
= (char **)(buffer
+ pos
);
364 pos
+= sizeof(char *);
366 /* copy addresses and fill new pointer list */
367 for (p
= s
->s_aliases
, q
= s_aliases
; *p
!= 0; p
++, q
++){
369 if (size
<= pos
+ len
)
373 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
374 buffer
[pos
+ len
] = '\0';
375 *q
= buffer
+ pos
; /* set copied pointer to copied content */
378 *++q
= 0; /* null terminate the pointer list */
379 s
->s_aliases
= s_aliases
; /* copy pointer to pointers */
382 #endif // HAVE_GETSERVBYNAME
384 servent
*wxGetservbyname_r(const char *port
,
385 const char *protocol
,
387 wxGetservBuf
& buffer
,
391 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
392 getservbyname_r(port
, protocol
, serv
, buffer
, size
, &se
);
393 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
394 se
= getservbyname_r(port
, protocol
, serv
, buffer
, size
);
395 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
396 if ( getservbyname_r(port
, protocol
, serv
, &buffer
) != 0 )
398 #elif defined(HAVE_GETSERVBYNAME)
399 wxLOCK_GETBY_MUTEX(serv
);
401 se
= getservbyname(port
, protocol
);
403 se
= deepCopyServent(serv
, se
, buffer
, size
);
405 #error "No getservbyname[_r]()"
410 } // anonymous namespace
412 // ============================================================================
413 // wxSockAddressImpl implementation
414 // ============================================================================
416 // FIXME-VC6: helper macros to call Alloc/Get() hiding the ugly dummy argument
417 #define ALLOC(T) Alloc(static_cast<T *>(NULL))
418 #define GET(T) Get(static_cast<T *>(NULL))
420 // ----------------------------------------------------------------------------
421 // INET or INET6 address family
422 // ----------------------------------------------------------------------------
424 wxString
wxSockAddressImpl::GetHostName() const
430 if ( m_family
== FAMILY_INET6
)
432 sockaddr_in6
* const addr6
= GET(sockaddr_in6
);
433 addrbuf
= &addr6
->sin6_addr
;
434 addrbuflen
= sizeof(addr6
->sin6_addr
);
439 sockaddr_in
* const addr
= GET(sockaddr_in
);
443 addrbuf
= &addr
->sin_addr
;
444 addrbuflen
= sizeof(addr
->sin_addr
);
450 if ( !wxGethostbyaddr_r
452 static_cast<const char *>(addrbuf
),
464 return wxString::FromUTF8(he
.h_name
);
467 bool wxSockAddressImpl::SetPortName(const wxString
& name
, const char *protocol
)
469 // test whether it's a number first
471 if ( name
.ToULong(&port
) )
476 else // it's a service name
480 if ( !wxGetservbyname_r(name
.utf8_str(), protocol
, &se
,
481 buffer
, sizeof(buffer
)) )
484 // s_port is in network byte order and SetPort() uses the host byte
485 // order and we prefer to reuse it from here instead of assigning to
487 port
= ntohs(se
.s_port
);
490 return SetPort(port
);
493 // ----------------------------------------------------------------------------
494 // INET address family
495 // ----------------------------------------------------------------------------
497 void wxSockAddressImpl::CreateINET()
499 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
501 m_family
= FAMILY_INET
;
502 sockaddr_in
* const addr
= ALLOC(sockaddr_in
);
503 addr
->sin_family
= FAMILY_INET
;
506 bool wxSockAddressImpl::SetHostName4(const wxString
& name
)
508 sockaddr_in
* const addr
= GET(sockaddr_in
);
512 const wxScopedCharBuffer
namebuf(name
.utf8_str());
514 // first check if this is an address in quad dotted notation
515 #if defined(HAVE_INET_ATON)
516 if ( inet_aton(namebuf
, &addr
->sin_addr
) )
518 #elif defined(HAVE_INET_ADDR)
519 addr
->sin_addr
.s_addr
= inet_addr(namebuf
);
520 if ( addr
->sin_addr
.s_addr
!= INADDR_NONE
)
523 #error "Neither inet_aton() nor inet_addr() is available?"
526 // it's a host name, resolve it
530 if ( !wxGethostbyname_r(namebuf
, &he
, buffer
, sizeof(buffer
), &err
) )
533 addr
->sin_addr
.s_addr
= ((in_addr
*)he
.h_addr
)->s_addr
;
537 bool wxSockAddressImpl::GetHostAddress(wxUint32
*address
) const
539 sockaddr_in
* const addr
= GET(sockaddr_in
);
543 *address
= ntohl(addr
->sin_addr
.s_addr
);
548 bool wxSockAddressImpl::SetHostAddress(wxUint32 address
)
550 sockaddr_in
* const addr
= GET(sockaddr_in
);
554 addr
->sin_addr
.s_addr
= htonl(address
);
559 wxUint16
wxSockAddressImpl::GetPort4() const
561 sockaddr_in
* const addr
= GET(sockaddr_in
);
565 return ntohs(addr
->sin_port
);
568 bool wxSockAddressImpl::SetPort4(wxUint16 port
)
570 sockaddr_in
* const addr
= GET(sockaddr_in
);
574 addr
->sin_port
= htons(port
);
581 // ----------------------------------------------------------------------------
582 // INET6 address family
583 // ----------------------------------------------------------------------------
585 void wxSockAddressImpl::CreateINET6()
587 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
589 m_family
= FAMILY_INET6
;
590 sockaddr_in6
* const addr
= ALLOC(sockaddr_in6
);
591 addr
->sin6_family
= FAMILY_INET6
;
594 bool wxSockAddressImpl::SetHostName6(const wxString
& hostname
)
596 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
601 memset(&hints
, 0, sizeof(hints
));
602 hints
.ai_family
= AF_INET6
;
604 addrinfo
*info
= NULL
;
605 int rc
= getaddrinfo(hostname
.utf8_str(), NULL
, &hints
, &info
);
608 // use gai_strerror()?
612 wxCHECK_MSG( info
, false, "should have info on success" );
614 wxASSERT_MSG( int(info
->ai_addrlen
) == m_len
, "unexpected address length" );
616 memcpy(addr
, info
->ai_addr
, info
->ai_addrlen
);
622 bool wxSockAddressImpl::GetHostAddress(in6_addr
*address
) const
624 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
628 *address
= addr
->sin6_addr
;
633 bool wxSockAddressImpl::SetHostAddress(const in6_addr
& address
)
635 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
639 addr
->sin6_addr
= address
;
644 wxUint16
wxSockAddressImpl::GetPort6() const
646 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
650 return ntohs(addr
->sin6_port
);
653 bool wxSockAddressImpl::SetPort6(wxUint16 port
)
655 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
659 addr
->sin6_port
= htons(port
);
664 bool wxSockAddressImpl::SetToAnyAddress6()
666 static const in6_addr any
= IN6ADDR_ANY_INIT
;
668 return SetHostAddress(any
);
673 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
675 // ----------------------------------------------------------------------------
676 // Unix address family
677 // ----------------------------------------------------------------------------
679 #ifndef UNIX_PATH_MAX
680 #define UNIX_PATH_MAX (WXSIZEOF(((sockaddr_un *)NULL)->sun_path))
683 void wxSockAddressImpl::CreateUnix()
685 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
687 m_family
= FAMILY_UNIX
;
688 sockaddr_un
* const addr
= ALLOC(sockaddr_un
);
689 addr
->sun_family
= FAMILY_UNIX
;
690 addr
->sun_path
[0] = '\0';
693 bool wxSockAddressImpl::SetPath(const wxString
& path
)
695 sockaddr_un
* const addr
= GET(sockaddr_un
);
699 const wxScopedCharBuffer
buf(path
.utf8_str());
700 if ( strlen(buf
) >= UNIX_PATH_MAX
)
703 wxStrlcpy(addr
->sun_path
, buf
, UNIX_PATH_MAX
);
708 wxString
wxSockAddressImpl::GetPath() const
710 sockaddr_un
* const addr
= GET(sockaddr_un
);
714 return wxString::FromUTF8(addr
->sun_path
);
717 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
722 // ----------------------------------------------------------------------------
724 // ----------------------------------------------------------------------------
726 const sockaddr
*wxSockAddress::GetAddressData() const
728 return GetAddress().GetAddr();
731 int wxSockAddress::GetAddressDataLen() const
733 return GetAddress().GetLen();
736 void wxSockAddress::Init()
738 if ( wxIsMainThread() && !wxSocketBase::IsInitialized() )
740 // we must do it before using any socket functions
741 (void)wxSocketBase::Initialize();
745 wxSockAddress::wxSockAddress()
749 m_impl
= new wxSockAddressImpl();
752 wxSockAddress::wxSockAddress(const wxSockAddress
& other
)
757 m_impl
= new wxSockAddressImpl(*other
.m_impl
);
760 wxSockAddress::~wxSockAddress()
765 void wxSockAddress::SetAddress(const wxSockAddressImpl
& address
)
767 if ( &address
!= m_impl
)
770 m_impl
= new wxSockAddressImpl(address
);
774 wxSockAddress
& wxSockAddress::operator=(const wxSockAddress
& addr
)
776 SetAddress(addr
.GetAddress());
781 void wxSockAddress::Clear()
786 // ----------------------------------------------------------------------------
788 // ----------------------------------------------------------------------------
790 wxSockAddressImpl
& wxIPaddress::GetImpl()
792 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
793 m_impl
->CreateINET();
798 bool wxIPaddress::Hostname(const wxString
& name
)
800 wxCHECK_MSG( !name
.empty(), false, "empty host name is invalid" );
802 m_origHostname
= name
;
804 return GetImpl().SetHostName(name
);
807 bool wxIPaddress::Service(const wxString
& name
)
809 return GetImpl().SetPortName(name
, "tcp");
812 bool wxIPaddress::Service(unsigned short port
)
814 return GetImpl().SetPort(port
);
817 bool wxIPaddress::LocalHost()
819 return Hostname("localhost");
822 wxString
wxIPaddress::Hostname() const
824 return GetImpl().GetHostName();
827 unsigned short wxIPaddress::Service() const
829 return GetImpl().GetPort();
832 bool wxIPaddress::operator==(const wxIPaddress
& addr
) const
834 return Hostname().Cmp(addr
.Hostname()) == 0 &&
835 Service() == addr
.Service();
838 bool wxIPaddress::AnyAddress()
840 return GetImpl().SetToAnyAddress();
843 // ----------------------------------------------------------------------------
845 // ----------------------------------------------------------------------------
847 void wxIPV4address::DoInitImpl()
849 m_impl
->CreateINET();
852 bool wxIPV4address::Hostname(unsigned long addr
)
854 if ( !GetImpl().SetHostAddress(addr
) )
856 m_origHostname
.clear();
860 m_origHostname
= Hostname();
864 bool wxIPV4address::IsLocalHost() const
866 return Hostname() == "localhost" || IPAddress() == "127.0.0.1";
869 wxString
wxIPV4address::IPAddress() const
872 if ( !GetImpl().GetHostAddress(&addr
) )
875 return wxString::Format
885 bool wxIPV4address::BroadcastAddress()
887 return GetImpl().SetToBroadcastAddress();
892 // ---------------------------------------------------------------------------
894 // ---------------------------------------------------------------------------
896 void wxIPV6address::DoInitImpl()
898 m_impl
->CreateINET6();
901 bool wxIPV6address::Hostname(unsigned char addr
[16])
903 unsigned short wk
[8];
904 for ( int i
= 0; i
< 8; ++i
)
908 wk
[i
] |= addr
[2*i
+1];
915 "%x:%x:%x:%x:%x:%x:%x:%x",
916 wk
[0], wk
[1], wk
[2], wk
[3], wk
[4], wk
[5], wk
[6], wk
[7]
921 bool wxIPV6address::IsLocalHost() const
923 if ( Hostname() == "localhost" )
926 wxString addr
= IPAddress();
927 return addr
== wxT("::1") ||
928 addr
== wxT("0:0:0:0:0:0:0:1") ||
929 addr
== wxT("::ffff:127.0.0.1");
932 wxString
wxIPV6address::IPAddress() const
940 if ( !GetImpl().GetHostAddress(&u
.addr6
) )
943 const wxUint8
* const addr
= u
.bytes
;
947 prefix_zero_count
= 0;
948 for ( i
= 0; i
< 8; ++i
)
950 words
[i
] = addr
[i
*2];
952 words
[i
] |= addr
[i
*2+1];
953 if ( i
== prefix_zero_count
&& words
[i
] == 0 )
958 if ( prefix_zero_count
== 8 )
960 result
= wxT( "::" );
962 else if ( prefix_zero_count
== 6 && words
[5] == 0xFFFF )
965 result
.Printf("::ffff:%d.%d.%d.%d",
966 addr
[12], addr
[13], addr
[14], addr
[15]);
971 for ( i
= prefix_zero_count
; i
< 8; ++i
)
973 result
+= wxString::Format(":%x", words
[i
]);
982 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
984 // ---------------------------------------------------------------------------
986 // ---------------------------------------------------------------------------
988 wxSockAddressImpl
& wxUNIXaddress::GetUNIX()
990 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
991 m_impl
->CreateUnix();
996 void wxUNIXaddress::Filename(const wxString
& fname
)
998 GetUNIX().SetPath(fname
);
1001 wxString
wxUNIXaddress::Filename() const
1003 return GetUNIX().GetPath();
1006 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
1008 #endif // wxUSE_SOCKETS