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"
39 #if !defined(__MWERKS__)
44 #include "wx/socket.h"
45 #include "wx/sckaddr.h"
46 #include "wx/private/socket.h"
47 #include "wx/private/sckaddr.h"
52 #include <arpa/inet.h>
56 #define INADDR_NONE INADDR_ANY
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 IMPLEMENT_ABSTRACT_CLASS(wxSockAddress
, wxObject
)
64 IMPLEMENT_ABSTRACT_CLASS(wxIPaddress
, wxSockAddress
)
65 IMPLEMENT_DYNAMIC_CLASS(wxIPV4address
, wxIPaddress
)
67 IMPLEMENT_DYNAMIC_CLASS(wxIPV6address
, wxIPaddress
)
69 #if defined(__UNIX__) && !defined(__WINDOWS__) && !defined(__WINE__)
70 IMPLEMENT_DYNAMIC_CLASS(wxUNIXaddress
, wxSockAddress
)
73 // ============================================================================
74 // implementation of thread-safe/reentrant functions if they're missing
75 // ============================================================================
77 // TODO: use POSIX getaddrinfo() (also available in Winsock 2) for simplicity
78 // and to use the same code for IPv4 and IPv6 support
81 #define HAVE_INET_ADDR
83 #define HAVE_GETHOSTBYNAME
84 #define HAVE_GETSERVBYNAME
86 // under MSW getxxxbyname() functions are MT-safe (but not reentrant) so
87 // we don't need to serialize calls to them
88 #define wxHAS_MT_SAFE_GETBY_FUNCS
91 // this header does dynamic dispatching of getaddrinfo/freeaddrinfo()
92 // by implementing them in its own code if the system versions are not
93 // available (as is the case for anything < XP)
95 // NB: if this is not available for the other compilers (so far tested
96 // with MSVC only) we should just use wxDynamicLibrary "manually"
98 // disable a warning occurring in Microsoft own version of this file
99 #pragma warning(disable:4706)
103 #pragma warning(default:4706)
108 // we assume that we have gethostbyaddr_r() if and only if we have
109 // gethostbyname_r() and that it uses the similar conventions to it (see
110 // comment in configure)
111 #define HAVE_GETHOSTBYADDR HAVE_GETHOSTBYNAME
112 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
113 #define HAVE_FUNC_GETHOSTBYADDR_R_3
115 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_5
116 #define HAVE_FUNC_GETHOSTBYADDR_R_5
118 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_6
119 #define HAVE_FUNC_GETHOSTBYADDR_R_6
122 // the _r functions need the extra buffer parameter but unfortunately its type
123 // differs between different systems
124 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
125 typedef hostent_data wxGethostBuf
;
127 typedef char wxGethostBuf
[1024];
130 #ifdef HAVE_FUNC_GETSERVBYNAME_R_3
131 typedef servent_data wxGetservBuf
;
133 typedef char wxGetservBuf
[1024];
136 #ifdef wxHAS_MT_SAFE_GETBY_FUNCS
137 #define wxLOCK_GETBY_MUTEX(name)
138 #else // may need mutexes to protect getxxxbyxxx() calls
139 #if defined(HAVE_GETHOSTBYNAME) || \
140 defined(HAVE_GETHOSTBYADDR) || \
141 defined(HAVE_GETSERVBYNAME)
142 #include "wx/thread.h"
146 // these mutexes are used to serialize
147 wxMutex nameLock
, // gethostbyname()
148 addrLock
, // gethostbyaddr()
149 servLock
; // getservbyname()
152 #define wxLOCK_GETBY_MUTEX(name) wxMutexLocker locker(name ## Lock)
153 #endif // we don't have _r functions
154 #endif // wxUSE_THREADS
159 #if defined(HAVE_GETHOSTBYNAME)
160 hostent
*deepCopyHostent(hostent
*h
,
166 /* copy old structure */
167 memcpy(h
, he
, sizeof(hostent
));
170 int len
= strlen(h
->h_name
);
176 memcpy(buffer
, h
->h_name
, len
);
180 /* track position in the buffer */
183 /* reuse len to store address length */
186 /* ensure pointer alignment */
187 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
188 if(misalign
< sizeof(char *))
191 /* leave space for pointer list */
192 char **p
= h
->h_addr_list
, **q
;
193 char **h_addr_list
= (char **)(buffer
+ pos
);
195 pos
+= sizeof(char *);
197 /* copy addresses and fill new pointer list */
198 for (p
= h
->h_addr_list
, q
= h_addr_list
; *p
!= 0; p
++, q
++)
200 if (size
< pos
+ len
)
205 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
206 *q
= buffer
+ pos
; /* set copied pointer to copied content */
209 *++q
= 0; /* null terminate the pointer list */
210 h
->h_addr_list
= h_addr_list
; /* copy pointer to pointers */
212 /* ensure word alignment of pointers */
213 misalign
= sizeof(char *) - pos%sizeof
(char *);
214 if(misalign
< sizeof(char *))
217 /* leave space for pointer list */
219 char **h_aliases
= (char **)(buffer
+ pos
);
221 pos
+= sizeof(char *);
223 /* copy aliases and fill new pointer list */
224 for (p
= h
->h_aliases
, q
= h_aliases
; *p
!= 0; p
++, q
++)
227 if (size
<= pos
+ len
)
232 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
233 buffer
[pos
+ len
] = '\0';
234 *q
= buffer
+ pos
; /* set copied pointer to copied content */
237 *++q
= 0; /* null terminate the pointer list */
238 h
->h_aliases
= h_aliases
; /* copy pointer to pointers */
242 #endif // HAVE_GETHOSTBYNAME
244 hostent
*wxGethostbyname_r(const char *hostname
,
251 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
252 gethostbyname_r(hostname
, h
, buffer
, size
, &he
, err
);
253 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
254 he
= gethostbyname_r(hostname
, h
, buffer
, size
, err
);
255 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
256 he
= gethostbyname_r(hostname
, h
, &buffer
);
258 #elif defined(HAVE_GETHOSTBYNAME)
259 wxLOCK_GETBY_MUTEX(name
);
261 he
= gethostbyname(hostname
);
265 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
267 #error "No gethostbyname[_r]()"
273 hostent
*wxGethostbyaddr_r(const char *addr_buf
,
282 #if defined(HAVE_FUNC_GETHOSTBYADDR_R_6)
283 gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, &he
, err
);
284 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_5)
285 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, err
);
286 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_3)
287 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
);
289 #elif defined(HAVE_GETHOSTBYADDR)
290 wxLOCK_GETBY_MUTEX(addr
);
292 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
296 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
298 #error "No gethostbyaddr[_r]()"
304 #if defined(HAVE_GETSERVBYNAME)
305 servent
*deepCopyServent(servent
*s
,
310 /* copy plain old structure */
311 memcpy(s
, se
, sizeof(servent
));
314 int len
= strlen(s
->s_name
);
319 memcpy(buffer
, s
->s_name
, len
);
323 /* track position in the buffer */
327 len
= strlen(s
->s_proto
);
328 if (pos
+ len
>= size
)
332 memcpy(buffer
+ pos
, s
->s_proto
, len
);
333 buffer
[pos
+ len
] = '\0';
334 s
->s_proto
= buffer
+ pos
;
336 /* track position in the buffer */
339 /* ensure pointer alignment */
340 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
341 if(misalign
< sizeof(char *))
344 /* leave space for pointer list */
345 char **p
= s
->s_aliases
, **q
;
346 char **s_aliases
= (char **)(buffer
+ pos
);
348 pos
+= sizeof(char *);
350 /* copy addresses and fill new pointer list */
351 for (p
= s
->s_aliases
, q
= s_aliases
; *p
!= 0; p
++, q
++){
353 if (size
<= pos
+ len
)
357 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
358 buffer
[pos
+ len
] = '\0';
359 *q
= buffer
+ pos
; /* set copied pointer to copied content */
362 *++q
= 0; /* null terminate the pointer list */
363 s
->s_aliases
= s_aliases
; /* copy pointer to pointers */
366 #endif // HAVE_GETSERVBYNAME
368 servent
*wxGetservbyname_r(const char *port
,
369 const char *protocol
,
375 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
376 getservbyname_r(port
, protocol
, serv
, buffer
, size
, &se
);
377 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
378 se
= getservbyname_r(port
, protocol
, serv
, buffer
, size
);
379 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
380 se
= getservbyname_r(port
, protocol
, serv
, &buffer
);
381 #elif defined(HAVE_GETSERVBYNAME)
382 wxLOCK_GETBY_MUTEX(serv
);
384 se
= getservbyname(port
, protocol
);
386 se
= deepCopyServent(serv
, se
, buffer
, size
);
388 #error "No getservbyname[_r]()"
393 } // anonymous namespace
395 // ============================================================================
396 // wxSockAddressImpl implementation
397 // ============================================================================
399 // FIXME-VC6: helper macros to call Alloc/Get() hiding the ugly dummy argument
400 #define ALLOC(T) Alloc(static_cast<T *>(NULL))
401 #define GET(T) Get(static_cast<T *>(NULL))
403 // ----------------------------------------------------------------------------
404 // INET or INET6 address family
405 // ----------------------------------------------------------------------------
407 wxString
wxSockAddressImpl::GetHostName() const
413 if ( m_family
== FAMILY_INET6
)
415 sockaddr_in6
* const addr6
= GET(sockaddr_in6
);
416 addrbuf
= &addr6
->sin6_addr
;
417 addrbuflen
= sizeof(addr6
->sin6_addr
);
422 sockaddr_in
* const addr
= GET(sockaddr_in
);
426 addrbuf
= &addr
->sin_addr
;
427 addrbuflen
= sizeof(addr
->sin_addr
);
433 if ( !wxGethostbyaddr_r
435 static_cast<const char *>(addrbuf
),
447 return wxString::FromUTF8(he
.h_name
);
450 bool wxSockAddressImpl::SetPortName(const wxString
& name
, const char *protocol
)
452 // test whether it's a number first
454 if ( name
.ToULong(&port
) )
459 else // it's a service name
463 if ( !wxGetservbyname_r(name
.utf8_str(), protocol
, &se
,
464 buffer
, sizeof(buffer
)) )
467 // s_port is in network byte order and SetPort() uses the host byte
468 // order and we prefer to reuse it from here instead of assigning to
470 port
= ntohs(se
.s_port
);
473 return SetPort(port
);
476 // ----------------------------------------------------------------------------
477 // INET address family
478 // ----------------------------------------------------------------------------
480 void wxSockAddressImpl::CreateINET()
482 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
484 m_family
= FAMILY_INET
;
485 sockaddr_in
* const addr
= ALLOC(sockaddr_in
);
486 addr
->sin_family
= FAMILY_INET
;
489 bool wxSockAddressImpl::SetHostName4(const wxString
& name
)
491 sockaddr_in
* const addr
= GET(sockaddr_in
);
495 const wxUTF8Buf
namebuf(name
.utf8_str());
497 // first check if this is an address in quad dotted notation
498 #if defined(HAVE_INET_ATON)
499 if ( inet_aton(namebuf
, &addr
->sin_addr
) )
501 #elif defined(HAVE_INET_ADDR)
502 addr
->sin_addr
.s_addr
= inet_addr(namebuf
);
503 if ( addr
->sin_addr
.s_addr
!= INADDR_NONE
)
506 #error "Neither inet_aton() nor inet_addr() is available?"
509 // it's a host name, resolve it
513 if ( !wxGethostbyname_r(namebuf
, &he
, buffer
, sizeof(buffer
), &err
) )
516 addr
->sin_addr
.s_addr
= ((in_addr
*)he
.h_addr
)->s_addr
;
520 bool wxSockAddressImpl::GetHostAddress(wxUint32
*address
) const
522 sockaddr_in
* const addr
= GET(sockaddr_in
);
526 *address
= ntohl(addr
->sin_addr
.s_addr
);
531 bool wxSockAddressImpl::SetHostAddress(wxUint32 address
)
533 sockaddr_in
* const addr
= GET(sockaddr_in
);
537 addr
->sin_addr
.s_addr
= htonl(address
);
542 wxUint16
wxSockAddressImpl::GetPort4() const
544 sockaddr_in
* const addr
= GET(sockaddr_in
);
548 return ntohs(addr
->sin_port
);
551 bool wxSockAddressImpl::SetPort4(wxUint16 port
)
553 sockaddr_in
* const addr
= GET(sockaddr_in
);
557 addr
->sin_port
= htons(port
);
564 // ----------------------------------------------------------------------------
565 // INET6 address family
566 // ----------------------------------------------------------------------------
568 void wxSockAddressImpl::CreateINET6()
570 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
572 m_family
= FAMILY_INET6
;
573 sockaddr_in6
* const addr
= ALLOC(sockaddr_in6
);
574 addr
->sin6_family
= FAMILY_INET6
;
577 bool wxSockAddressImpl::SetHostName6(const wxString
& hostname
)
579 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
584 memset(&hints
, 0, sizeof(hints
));
585 hints
.ai_family
= AF_INET6
;
587 addrinfo
*info
= NULL
;
588 int rc
= getaddrinfo(hostname
.utf8_str(), NULL
, &hints
, &info
);
591 // use gai_strerror()?
595 wxCHECK_MSG( info
, false, "should have info on success" );
597 wxASSERT_MSG( int(info
->ai_addrlen
) == m_len
, "unexpected address length" );
599 memcpy(addr
, info
->ai_addr
, info
->ai_addrlen
);
605 bool wxSockAddressImpl::GetHostAddress(in6_addr
*address
) const
607 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
611 *address
= addr
->sin6_addr
;
616 bool wxSockAddressImpl::SetHostAddress(const in6_addr
& address
)
618 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
622 addr
->sin6_addr
= address
;
627 wxUint16
wxSockAddressImpl::GetPort6() const
629 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
633 return ntohs(addr
->sin6_port
);
636 bool wxSockAddressImpl::SetPort6(wxUint16 port
)
638 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
642 addr
->sin6_port
= htons(port
);
647 bool wxSockAddressImpl::SetToAnyAddress6()
649 static const in6_addr any
= IN6ADDR_ANY_INIT
;
651 return SetHostAddress(any
);
656 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
658 // ----------------------------------------------------------------------------
659 // Unix address family
660 // ----------------------------------------------------------------------------
662 #ifndef UNIX_PATH_MAX
663 #define UNIX_PATH_MAX (WXSIZEOF(((sockaddr_un *)NULL)->sun_path))
666 void wxSockAddressImpl::CreateUnix()
668 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
670 m_family
= FAMILY_UNIX
;
671 sockaddr_un
* const addr
= ALLOC(sockaddr_un
);
672 addr
->sun_family
= FAMILY_UNIX
;
673 addr
->sun_path
[0] = '\0';
676 bool wxSockAddressImpl::SetPath(const wxString
& path
)
678 sockaddr_un
* const addr
= GET(sockaddr_un
);
682 const wxUTF8Buf
buf(path
.utf8_str());
683 if ( strlen(buf
) >= UNIX_PATH_MAX
)
686 wxStrlcpy(addr
->sun_path
, buf
, UNIX_PATH_MAX
);
691 wxString
wxSockAddressImpl::GetPath() const
693 sockaddr_un
* const addr
= GET(sockaddr_un
);
697 return wxString::FromUTF8(addr
->sun_path
);
700 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
705 // ----------------------------------------------------------------------------
707 // ----------------------------------------------------------------------------
709 void wxSockAddress::Init()
711 if ( !wxSocketBase::IsInitialized() )
713 // we must do it before using any socket functions
714 (void)wxSocketBase::Initialize();
718 wxSockAddress::wxSockAddress()
722 m_impl
= new wxSockAddressImpl();
725 wxSockAddress::wxSockAddress(const wxSockAddress
& other
)
730 m_impl
= new wxSockAddressImpl(*other
.m_impl
);
733 wxSockAddress::~wxSockAddress()
738 void wxSockAddress::SetAddress(const wxSockAddressImpl
& address
)
740 if ( &address
!= m_impl
)
743 m_impl
= new wxSockAddressImpl(address
);
747 wxSockAddress
& wxSockAddress::operator=(const wxSockAddress
& addr
)
749 SetAddress(addr
.GetAddress());
754 void wxSockAddress::Clear()
759 // ----------------------------------------------------------------------------
761 // ----------------------------------------------------------------------------
763 wxSockAddressImpl
& wxIPaddress::GetImpl()
765 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
766 m_impl
->CreateINET();
771 bool wxIPaddress::Hostname(const wxString
& name
)
773 wxCHECK_MSG( !name
.empty(), false, "empty host name is invalid" );
775 m_origHostname
= name
;
777 return GetImpl().SetHostName(name
);
780 bool wxIPaddress::Service(const wxString
& name
)
782 return GetImpl().SetPortName(name
, "tcp");
785 bool wxIPaddress::Service(unsigned short port
)
787 return GetImpl().SetPort(port
);
790 bool wxIPaddress::LocalHost()
792 return Hostname("localhost");
795 wxString
wxIPaddress::Hostname() const
797 return GetImpl().GetHostName();
800 unsigned short wxIPaddress::Service() const
802 return GetImpl().GetPort();
805 bool wxIPaddress::operator==(const wxIPaddress
& addr
) const
807 return Hostname().Cmp(addr
.Hostname()) == 0 &&
808 Service() == addr
.Service();
811 bool wxIPaddress::AnyAddress()
813 return GetImpl().SetToAnyAddress();
816 // ----------------------------------------------------------------------------
818 // ----------------------------------------------------------------------------
820 void wxIPV4address::DoInitImpl()
822 m_impl
->CreateINET();
825 bool wxIPV4address::Hostname(unsigned long addr
)
827 if ( !GetImpl().SetHostAddress(addr
) )
829 m_origHostname
.clear();
833 m_origHostname
= Hostname();
837 bool wxIPV4address::IsLocalHost() const
839 return Hostname() == "localhost" || IPAddress() == "127.0.0.1";
842 wxString
wxIPV4address::IPAddress() const
845 if ( !GetImpl().GetHostAddress(&addr
) )
848 return wxString::Format
858 bool wxIPV4address::BroadcastAddress()
860 return GetImpl().SetToBroadcastAddress();
865 // ---------------------------------------------------------------------------
867 // ---------------------------------------------------------------------------
869 void wxIPV6address::DoInitImpl()
871 m_impl
->CreateINET6();
874 bool wxIPV6address::Hostname(unsigned char addr
[16])
876 unsigned short wk
[8];
877 for ( int i
= 0; i
< 8; ++i
)
881 wk
[i
] |= addr
[2*i
+1];
888 "%x:%x:%x:%x:%x:%x:%x:%x",
889 wk
[0], wk
[1], wk
[2], wk
[3], wk
[4], wk
[5], wk
[6], wk
[7]
894 bool wxIPV6address::IsLocalHost() const
896 if ( Hostname() == "localhost" )
899 wxString addr
= IPAddress();
900 return addr
== wxT("::1") ||
901 addr
== wxT("0:0:0:0:0:0:0:1") ||
902 addr
== wxT("::ffff:127.0.0.1");
905 wxString
wxIPV6address::IPAddress() const
913 if ( !GetImpl().GetHostAddress(&u
.addr6
) )
916 const wxUint8
* const addr
= u
.bytes
;
920 prefix_zero_count
= 0;
921 for ( i
= 0; i
< 8; ++i
)
923 words
[i
] = addr
[i
*2];
925 words
[i
] |= addr
[i
*2+1];
926 if ( i
== prefix_zero_count
&& words
[i
] == 0 )
931 if ( prefix_zero_count
== 8 )
933 result
= wxT( "::" );
935 else if ( prefix_zero_count
== 6 && words
[5] == 0xFFFF )
938 result
.Printf("::ffff:%d.%d.%d.%d",
939 addr
[12], addr
[13], addr
[14], addr
[15]);
944 for ( i
= prefix_zero_count
; i
< 8; ++i
)
946 result
+= wxString::Format(":%x", words
[i
]);
955 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
957 // ---------------------------------------------------------------------------
959 // ---------------------------------------------------------------------------
961 wxSockAddressImpl
& wxUNIXaddress::GetUNIX()
963 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
964 m_impl
->CreateUnix();
969 void wxUNIXaddress::Filename(const wxString
& fname
)
971 GetUNIX().SetPath(fname
);
974 wxString
wxUNIXaddress::Filename() const
976 return GetUNIX().GetPath();
979 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
981 #endif // wxUSE_SOCKETS