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"
53 #include <arpa/inet.h>
57 #define INADDR_NONE INADDR_ANY
60 // ----------------------------------------------------------------------------
62 // ----------------------------------------------------------------------------
64 IMPLEMENT_ABSTRACT_CLASS(wxSockAddress
, wxObject
)
65 IMPLEMENT_ABSTRACT_CLASS(wxIPaddress
, wxSockAddress
)
66 IMPLEMENT_DYNAMIC_CLASS(wxIPV4address
, wxIPaddress
)
68 IMPLEMENT_DYNAMIC_CLASS(wxIPV6address
, wxIPaddress
)
70 #if defined(__UNIX__) && !defined(__WINDOWS__) && !defined(__WINE__)
71 IMPLEMENT_DYNAMIC_CLASS(wxUNIXaddress
, wxSockAddress
)
74 // ============================================================================
75 // implementation of thread-safe/reentrant functions if they're missing
76 // ============================================================================
78 // TODO: use POSIX getaddrinfo() (also available in Winsock 2) for simplicity
79 // and to use the same code for IPv4 and IPv6 support
82 #define HAVE_INET_ADDR
84 #define HAVE_GETHOSTBYNAME
85 #define HAVE_GETSERVBYNAME
87 // under MSW getxxxbyname() functions are MT-safe (but not reentrant) so
88 // we don't need to serialize calls to them
89 #define wxHAS_MT_SAFE_GETBY_FUNCS
92 // this header does dynamic dispatching of getaddrinfo/freeaddrinfo()
93 // by implementing them in its own code if the system versions are not
94 // available (as is the case for anything < XP)
96 // NB: if this is not available for the other compilers (so far tested
97 // with MSVC only) we should just use wxDynamicLibrary "manually"
99 // disable a warning occurring in Microsoft own version of this file
100 #pragma warning(disable:4706)
104 #pragma warning(default:4706)
109 // we assume that we have gethostbyaddr_r() if and only if we have
110 // gethostbyname_r() and that it uses the similar conventions to it (see
111 // comment in configure)
112 #define HAVE_GETHOSTBYADDR HAVE_GETHOSTBYNAME
113 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
114 #define HAVE_FUNC_GETHOSTBYADDR_R_3
116 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_5
117 #define HAVE_FUNC_GETHOSTBYADDR_R_5
119 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_6
120 #define HAVE_FUNC_GETHOSTBYADDR_R_6
123 // the _r functions need the extra buffer parameter but unfortunately its type
124 // differs between different systems
125 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
126 typedef hostent_data wxGethostBuf
;
128 typedef char wxGethostBuf
[1024];
131 #ifdef HAVE_FUNC_GETSERVBYNAME_R_3
132 typedef servent_data wxGetservBuf
;
134 typedef char wxGetservBuf
[1024];
137 #ifdef wxHAS_MT_SAFE_GETBY_FUNCS
138 #define wxLOCK_GETBY_MUTEX(name)
139 #else // may need mutexes to protect getxxxbyxxx() calls
140 #if defined(HAVE_GETHOSTBYNAME) || \
141 defined(HAVE_GETHOSTBYADDR) || \
142 defined(HAVE_GETSERVBYNAME)
143 #include "wx/thread.h"
147 // these mutexes are used to serialize
148 wxMutex nameLock
, // gethostbyname()
149 addrLock
, // gethostbyaddr()
150 servLock
; // getservbyname()
153 #define wxLOCK_GETBY_MUTEX(name) wxMutexLocker locker(name ## Lock)
154 #endif // we don't have _r functions
155 #endif // wxUSE_THREADS
160 #if defined(HAVE_GETHOSTBYNAME)
161 hostent
*deepCopyHostent(hostent
*h
,
167 /* copy old structure */
168 memcpy(h
, he
, sizeof(hostent
));
171 int len
= strlen(h
->h_name
);
177 memcpy(buffer
, h
->h_name
, len
);
181 /* track position in the buffer */
184 /* reuse len to store address length */
187 /* ensure pointer alignment */
188 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
189 if(misalign
< sizeof(char *))
192 /* leave space for pointer list */
193 char **p
= h
->h_addr_list
, **q
;
194 char **h_addr_list
= (char **)(buffer
+ pos
);
196 pos
+= sizeof(char *);
198 /* copy addresses and fill new pointer list */
199 for (p
= h
->h_addr_list
, q
= h_addr_list
; *p
!= 0; p
++, q
++)
201 if (size
< pos
+ len
)
206 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
207 *q
= buffer
+ pos
; /* set copied pointer to copied content */
210 *++q
= 0; /* null terminate the pointer list */
211 h
->h_addr_list
= h_addr_list
; /* copy pointer to pointers */
213 /* ensure word alignment of pointers */
214 misalign
= sizeof(char *) - pos%sizeof
(char *);
215 if(misalign
< sizeof(char *))
218 /* leave space for pointer list */
220 char **h_aliases
= (char **)(buffer
+ pos
);
222 pos
+= sizeof(char *);
224 /* copy aliases and fill new pointer list */
225 for (p
= h
->h_aliases
, q
= h_aliases
; *p
!= 0; p
++, q
++)
228 if (size
<= pos
+ len
)
233 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
234 buffer
[pos
+ len
] = '\0';
235 *q
= buffer
+ pos
; /* set copied pointer to copied content */
238 *++q
= 0; /* null terminate the pointer list */
239 h
->h_aliases
= h_aliases
; /* copy pointer to pointers */
243 #endif // HAVE_GETHOSTBYNAME
245 hostent
*wxGethostbyname_r(const char *hostname
,
252 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
253 gethostbyname_r(hostname
, h
, buffer
, size
, &he
, err
);
254 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
255 he
= gethostbyname_r(hostname
, h
, buffer
, size
, err
);
256 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
257 he
= gethostbyname_r(hostname
, h
, &buffer
);
259 #elif defined(HAVE_GETHOSTBYNAME)
260 wxLOCK_GETBY_MUTEX(name
);
262 he
= gethostbyname(hostname
);
266 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
268 #error "No gethostbyname[_r]()"
274 hostent
*wxGethostbyaddr_r(const char *addr_buf
,
283 #if defined(HAVE_FUNC_GETHOSTBYADDR_R_6)
284 gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, &he
, err
);
285 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_5)
286 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, err
);
287 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_3)
288 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
);
290 #elif defined(HAVE_GETHOSTBYADDR)
291 wxLOCK_GETBY_MUTEX(addr
);
293 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
297 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
299 #error "No gethostbyaddr[_r]()"
305 #if defined(HAVE_GETSERVBYNAME)
306 servent
*deepCopyServent(servent
*s
,
311 /* copy plain old structure */
312 memcpy(s
, se
, sizeof(servent
));
315 int len
= strlen(s
->s_name
);
320 memcpy(buffer
, s
->s_name
, len
);
324 /* track position in the buffer */
328 len
= strlen(s
->s_proto
);
329 if (pos
+ len
>= size
)
333 memcpy(buffer
+ pos
, s
->s_proto
, len
);
334 buffer
[pos
+ len
] = '\0';
335 s
->s_proto
= buffer
+ pos
;
337 /* track position in the buffer */
340 /* ensure pointer alignment */
341 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
342 if(misalign
< sizeof(char *))
345 /* leave space for pointer list */
346 char **p
= s
->s_aliases
, **q
;
347 char **s_aliases
= (char **)(buffer
+ pos
);
349 pos
+= sizeof(char *);
351 /* copy addresses and fill new pointer list */
352 for (p
= s
->s_aliases
, q
= s_aliases
; *p
!= 0; p
++, q
++){
354 if (size
<= pos
+ len
)
358 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
359 buffer
[pos
+ len
] = '\0';
360 *q
= buffer
+ pos
; /* set copied pointer to copied content */
363 *++q
= 0; /* null terminate the pointer list */
364 s
->s_aliases
= s_aliases
; /* copy pointer to pointers */
367 #endif // HAVE_GETSERVBYNAME
369 servent
*wxGetservbyname_r(const char *port
,
370 const char *protocol
,
376 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
377 getservbyname_r(port
, protocol
, serv
, buffer
, size
, &se
);
378 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
379 se
= getservbyname_r(port
, protocol
, serv
, buffer
, size
);
380 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
381 se
= getservbyname_r(port
, protocol
, serv
, &buffer
);
382 #elif defined(HAVE_GETSERVBYNAME)
383 wxLOCK_GETBY_MUTEX(serv
);
385 se
= getservbyname(port
, protocol
);
387 se
= deepCopyServent(serv
, se
, buffer
, size
);
389 #error "No getservbyname[_r]()"
394 } // anonymous namespace
396 // ============================================================================
397 // wxSockAddressImpl implementation
398 // ============================================================================
400 // FIXME-VC6: helper macros to call Alloc/Get() hiding the ugly dummy argument
401 #define ALLOC(T) Alloc(static_cast<T *>(NULL))
402 #define GET(T) Get(static_cast<T *>(NULL))
404 // ----------------------------------------------------------------------------
405 // INET or INET6 address family
406 // ----------------------------------------------------------------------------
408 wxString
wxSockAddressImpl::GetHostName() const
414 if ( m_family
== FAMILY_INET6
)
416 sockaddr_in6
* const addr6
= GET(sockaddr_in6
);
417 addrbuf
= &addr6
->sin6_addr
;
418 addrbuflen
= sizeof(addr6
->sin6_addr
);
423 sockaddr_in
* const addr
= GET(sockaddr_in
);
427 addrbuf
= &addr
->sin_addr
;
428 addrbuflen
= sizeof(addr
->sin_addr
);
434 if ( !wxGethostbyaddr_r
436 static_cast<const char *>(addrbuf
),
448 return wxString::FromUTF8(he
.h_name
);
451 bool wxSockAddressImpl::SetPortName(const wxString
& name
, const char *protocol
)
453 // test whether it's a number first
455 if ( name
.ToULong(&port
) )
460 else // it's a service name
464 if ( !wxGetservbyname_r(name
.utf8_str(), protocol
, &se
,
465 buffer
, sizeof(buffer
)) )
468 // s_port is in network byte order and SetPort() uses the host byte
469 // order and we prefer to reuse it from here instead of assigning to
471 port
= ntohs(se
.s_port
);
474 return SetPort(port
);
477 // ----------------------------------------------------------------------------
478 // INET address family
479 // ----------------------------------------------------------------------------
481 void wxSockAddressImpl::CreateINET()
483 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
485 m_family
= FAMILY_INET
;
486 sockaddr_in
* const addr
= ALLOC(sockaddr_in
);
487 addr
->sin_family
= FAMILY_INET
;
490 bool wxSockAddressImpl::SetHostName4(const wxString
& name
)
492 sockaddr_in
* const addr
= GET(sockaddr_in
);
496 const wxUTF8Buf
namebuf(name
.utf8_str());
498 // first check if this is an address in quad dotted notation
499 #if defined(HAVE_INET_ATON)
500 if ( inet_aton(namebuf
, &addr
->sin_addr
) )
502 #elif defined(HAVE_INET_ADDR)
503 addr
->sin_addr
.s_addr
= inet_addr(namebuf
);
504 if ( addr
->sin_addr
.s_addr
!= INADDR_NONE
)
507 #error "Neither inet_aton() nor inet_addr() is available?"
510 // it's a host name, resolve it
514 if ( !wxGethostbyname_r(namebuf
, &he
, buffer
, sizeof(buffer
), &err
) )
517 addr
->sin_addr
.s_addr
= ((in_addr
*)he
.h_addr
)->s_addr
;
521 bool wxSockAddressImpl::GetHostAddress(wxUint32
*address
) const
523 sockaddr_in
* const addr
= GET(sockaddr_in
);
527 *address
= ntohl(addr
->sin_addr
.s_addr
);
532 bool wxSockAddressImpl::SetHostAddress(wxUint32 address
)
534 sockaddr_in
* const addr
= GET(sockaddr_in
);
538 addr
->sin_addr
.s_addr
= htonl(address
);
543 wxUint16
wxSockAddressImpl::GetPort4() const
545 sockaddr_in
* const addr
= GET(sockaddr_in
);
549 return ntohs(addr
->sin_port
);
552 bool wxSockAddressImpl::SetPort4(wxUint16 port
)
554 sockaddr_in
* const addr
= GET(sockaddr_in
);
558 addr
->sin_port
= htons(port
);
565 // ----------------------------------------------------------------------------
566 // INET6 address family
567 // ----------------------------------------------------------------------------
569 void wxSockAddressImpl::CreateINET6()
571 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
573 m_family
= FAMILY_INET6
;
574 sockaddr_in6
* const addr
= ALLOC(sockaddr_in6
);
575 addr
->sin6_family
= FAMILY_INET6
;
578 bool wxSockAddressImpl::SetHostName6(const wxString
& hostname
)
580 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
585 memset(&hints
, 0, sizeof(hints
));
586 hints
.ai_family
= AF_INET6
;
588 addrinfo
*info
= NULL
;
589 int rc
= getaddrinfo(hostname
.utf8_str(), NULL
, &hints
, &info
);
592 // use gai_strerror()?
596 wxCHECK_MSG( info
, false, "should have info on success" );
598 wxASSERT_MSG( int(info
->ai_addrlen
) == m_len
, "unexpected address length" );
600 memcpy(addr
, info
->ai_addr
, info
->ai_addrlen
);
606 bool wxSockAddressImpl::GetHostAddress(in6_addr
*address
) const
608 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
612 *address
= addr
->sin6_addr
;
617 bool wxSockAddressImpl::SetHostAddress(const in6_addr
& address
)
619 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
623 addr
->sin6_addr
= address
;
628 wxUint16
wxSockAddressImpl::GetPort6() const
630 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
634 return ntohs(addr
->sin6_port
);
637 bool wxSockAddressImpl::SetPort6(wxUint16 port
)
639 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
643 addr
->sin6_port
= htons(port
);
648 bool wxSockAddressImpl::SetToAnyAddress6()
650 static const in6_addr any
= IN6ADDR_ANY_INIT
;
652 return SetHostAddress(any
);
657 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
659 // ----------------------------------------------------------------------------
660 // Unix address family
661 // ----------------------------------------------------------------------------
663 #ifndef UNIX_PATH_MAX
664 #define UNIX_PATH_MAX (WXSIZEOF(((sockaddr_un *)NULL)->sun_path))
667 void wxSockAddressImpl::CreateUnix()
669 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
671 m_family
= FAMILY_UNIX
;
672 sockaddr_un
* const addr
= ALLOC(sockaddr_un
);
673 addr
->sun_family
= FAMILY_UNIX
;
674 addr
->sun_path
[0] = '\0';
677 bool wxSockAddressImpl::SetPath(const wxString
& path
)
679 sockaddr_un
* const addr
= GET(sockaddr_un
);
683 const wxUTF8Buf
buf(path
.utf8_str());
684 if ( strlen(buf
) >= UNIX_PATH_MAX
)
687 wxStrlcpy(addr
->sun_path
, buf
, UNIX_PATH_MAX
);
692 wxString
wxSockAddressImpl::GetPath() const
694 sockaddr_un
* const addr
= GET(sockaddr_un
);
698 return wxString::FromUTF8(addr
->sun_path
);
701 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
706 // ----------------------------------------------------------------------------
708 // ----------------------------------------------------------------------------
710 void wxSockAddress::Init()
712 if ( !wxSocketBase::IsInitialized() )
714 // we must do it before using any socket functions
715 (void)wxSocketBase::Initialize();
719 wxSockAddress::wxSockAddress()
723 m_impl
= new wxSockAddressImpl();
726 wxSockAddress::wxSockAddress(const wxSockAddress
& other
)
731 m_impl
= new wxSockAddressImpl(*other
.m_impl
);
734 wxSockAddress::~wxSockAddress()
739 void wxSockAddress::SetAddress(const wxSockAddressImpl
& address
)
741 if ( &address
!= m_impl
)
744 m_impl
= new wxSockAddressImpl(address
);
748 wxSockAddress
& wxSockAddress::operator=(const wxSockAddress
& addr
)
750 SetAddress(addr
.GetAddress());
755 void wxSockAddress::Clear()
760 // ----------------------------------------------------------------------------
762 // ----------------------------------------------------------------------------
764 wxSockAddressImpl
& wxIPaddress::GetImpl()
766 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
767 m_impl
->CreateINET();
772 bool wxIPaddress::Hostname(const wxString
& name
)
774 wxCHECK_MSG( !name
.empty(), false, "empty host name is invalid" );
776 m_origHostname
= name
;
778 return GetImpl().SetHostName(name
);
781 bool wxIPaddress::Service(const wxString
& name
)
783 return GetImpl().SetPortName(name
, "tcp");
786 bool wxIPaddress::Service(unsigned short port
)
788 return GetImpl().SetPort(port
);
791 bool wxIPaddress::LocalHost()
793 return Hostname("localhost");
796 wxString
wxIPaddress::Hostname() const
798 return GetImpl().GetHostName();
801 unsigned short wxIPaddress::Service() const
803 return GetImpl().GetPort();
806 bool wxIPaddress::operator==(const wxIPaddress
& addr
) const
808 return Hostname().Cmp(addr
.Hostname()) == 0 &&
809 Service() == addr
.Service();
812 bool wxIPaddress::AnyAddress()
814 return GetImpl().SetToAnyAddress();
817 // ----------------------------------------------------------------------------
819 // ----------------------------------------------------------------------------
821 void wxIPV4address::DoInitImpl()
823 m_impl
->CreateINET();
826 bool wxIPV4address::Hostname(unsigned long addr
)
828 if ( !GetImpl().SetHostAddress(addr
) )
830 m_origHostname
.clear();
834 m_origHostname
= Hostname();
838 bool wxIPV4address::IsLocalHost() const
840 return Hostname() == "localhost" || IPAddress() == "127.0.0.1";
843 wxString
wxIPV4address::IPAddress() const
846 if ( !GetImpl().GetHostAddress(&addr
) )
849 return wxString::Format
859 bool wxIPV4address::BroadcastAddress()
861 return GetImpl().SetToBroadcastAddress();
866 // ---------------------------------------------------------------------------
868 // ---------------------------------------------------------------------------
870 void wxIPV6address::DoInitImpl()
872 m_impl
->CreateINET6();
875 bool wxIPV6address::Hostname(unsigned char addr
[16])
877 unsigned short wk
[8];
878 for ( int i
= 0; i
< 8; ++i
)
882 wk
[i
] |= addr
[2*i
+1];
889 "%x:%x:%x:%x:%x:%x:%x:%x",
890 wk
[0], wk
[1], wk
[2], wk
[3], wk
[4], wk
[5], wk
[6], wk
[7]
895 bool wxIPV6address::IsLocalHost() const
897 if ( Hostname() == "localhost" )
900 wxString addr
= IPAddress();
901 return addr
== wxT("::1") ||
902 addr
== wxT("0:0:0:0:0:0:0:1") ||
903 addr
== wxT("::ffff:127.0.0.1");
906 wxString
wxIPV6address::IPAddress() const
914 if ( !GetImpl().GetHostAddress(&u
.addr6
) )
917 const wxUint8
* const addr
= u
.bytes
;
921 prefix_zero_count
= 0;
922 for ( i
= 0; i
< 8; ++i
)
924 words
[i
] = addr
[i
*2];
926 words
[i
] |= addr
[i
*2+1];
927 if ( i
== prefix_zero_count
&& words
[i
] == 0 )
932 if ( prefix_zero_count
== 8 )
934 result
= wxT( "::" );
936 else if ( prefix_zero_count
== 6 && words
[5] == 0xFFFF )
939 result
.Printf("::ffff:%d.%d.%d.%d",
940 addr
[12], addr
[13], addr
[14], addr
[15]);
945 for ( i
= prefix_zero_count
; i
< 8; ++i
)
947 result
+= wxString::Format(":%x", words
[i
]);
956 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
958 // ---------------------------------------------------------------------------
960 // ---------------------------------------------------------------------------
962 wxSockAddressImpl
& wxUNIXaddress::GetUNIX()
964 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
965 m_impl
->CreateUnix();
970 void wxUNIXaddress::Filename(const wxString
& fname
)
972 GetUNIX().SetPath(fname
);
975 wxString
wxUNIXaddress::Filename() const
977 return GetUNIX().GetPath();
980 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
982 #endif // wxUSE_SOCKETS