]>
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
7 // Copyright: (c) 1997, 1998 Guilhem Lavaux
8 // (c) 2008 Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
30 #include "wx/object.h"
33 #include "wx/thread.h"
42 #include "wx/socket.h"
43 #include "wx/sckaddr.h"
44 #include "wx/private/socket.h"
45 #include "wx/private/sckaddr.h"
49 #if defined(__UNIX__) && !defined(__WXMSW__)
51 #include <arpa/inet.h>
55 #define INADDR_NONE INADDR_ANY
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 IMPLEMENT_ABSTRACT_CLASS(wxSockAddress
, wxObject
)
63 IMPLEMENT_ABSTRACT_CLASS(wxIPaddress
, wxSockAddress
)
64 IMPLEMENT_DYNAMIC_CLASS(wxIPV4address
, wxIPaddress
)
66 IMPLEMENT_DYNAMIC_CLASS(wxIPV6address
, wxIPaddress
)
68 #if defined(__UNIX__) && !defined(__WINDOWS__) && !defined(__WINE__)
69 IMPLEMENT_DYNAMIC_CLASS(wxUNIXaddress
, wxSockAddress
)
72 // ============================================================================
73 // implementation of thread-safe/reentrant functions if they're missing
74 // ============================================================================
76 // TODO: use POSIX getaddrinfo() (also available in Winsock 2) for simplicity
77 // and to use the same code for IPv4 and IPv6 support
80 #define HAVE_INET_ADDR
82 #ifndef HAVE_GETHOSTBYNAME
83 #define HAVE_GETHOSTBYNAME
85 #ifndef HAVE_GETSERVBYNAME
86 #define HAVE_GETSERVBYNAME
89 // under MSW getxxxbyname() functions are MT-safe (but not reentrant) so
90 // we don't need to serialize calls to them
91 #define wxHAS_MT_SAFE_GETBY_FUNCS
95 // this header does dynamic dispatching of getaddrinfo/freeaddrinfo()
96 // by implementing them in its own code if the system versions are
97 // not available (as is the case for anything < XP)
99 #pragma warning(disable:4706)
103 // TODO: Use wxDynamicLibrary to bind to these functions
104 // dynamically on older Windows systems, currently a program
105 // built with wxUSE_IPV6==1 won't even start there, even if
106 // it doesn't actually use the socket stuff.
107 #include <ws2tcpip.h>
110 #endif // __WINDOWS__
112 // we assume that we have gethostbyaddr_r() if and only if we have
113 // gethostbyname_r() and that it uses the similar conventions to it (see
114 // comment in configure)
115 #define HAVE_GETHOSTBYADDR HAVE_GETHOSTBYNAME
116 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
117 #define HAVE_FUNC_GETHOSTBYADDR_R_3
119 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_5
120 #define HAVE_FUNC_GETHOSTBYADDR_R_5
122 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_6
123 #define HAVE_FUNC_GETHOSTBYADDR_R_6
126 // the _r functions need the extra buffer parameter but unfortunately its type
127 // differs between different systems and for the systems which use opaque
128 // structs for it (at least AIX and OpenBSD) it must be zero-filled before
129 // being passed to the system functions
130 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
131 struct wxGethostBuf
: hostent_data
135 memset(this, 0, sizeof(hostent_data
));
139 typedef char wxGethostBuf
[1024];
142 #ifdef HAVE_FUNC_GETSERVBYNAME_R_4
143 struct wxGetservBuf
: servent_data
147 memset(this, 0, sizeof(servent_data
));
151 typedef char wxGetservBuf
[1024];
154 #if defined(wxHAS_MT_SAFE_GETBY_FUNCS) || !wxUSE_THREADS
155 #define wxLOCK_GETBY_MUTEX(name)
156 #else // may need mutexes to protect getxxxbyxxx() calls
157 #if defined(HAVE_GETHOSTBYNAME) || \
158 defined(HAVE_GETHOSTBYADDR) || \
159 defined(HAVE_GETSERVBYNAME)
160 #include "wx/thread.h"
164 // these mutexes are used to serialize
165 wxMutex nameLock
, // gethostbyname()
166 addrLock
, // gethostbyaddr()
167 servLock
; // getservbyname()
170 #define wxLOCK_GETBY_MUTEX(name) wxMutexLocker locker(name ## Lock)
171 #endif // we don't have _r functions
172 #endif // wxUSE_THREADS
177 #if defined(HAVE_GETHOSTBYNAME)
178 hostent
*deepCopyHostent(hostent
*h
,
184 /* copy old structure */
185 memcpy(h
, he
, sizeof(hostent
));
188 int len
= strlen(h
->h_name
);
194 memcpy(buffer
, h
->h_name
, len
);
198 /* track position in the buffer */
201 /* reuse len to store address length */
204 /* ensure pointer alignment */
205 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
206 if(misalign
< sizeof(char *))
209 /* leave space for pointer list */
210 char **p
= h
->h_addr_list
, **q
;
211 char **h_addr_list
= (char **)(buffer
+ pos
);
213 pos
+= sizeof(char *);
215 /* copy addresses and fill new pointer list */
216 for (p
= h
->h_addr_list
, q
= h_addr_list
; *p
!= 0; p
++, q
++)
218 if (size
< pos
+ len
)
223 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
224 *q
= buffer
+ pos
; /* set copied pointer to copied content */
227 *++q
= 0; /* null terminate the pointer list */
228 h
->h_addr_list
= h_addr_list
; /* copy pointer to pointers */
230 /* ensure word alignment of pointers */
231 misalign
= sizeof(char *) - pos%sizeof
(char *);
232 if(misalign
< sizeof(char *))
235 /* leave space for pointer list */
237 char **h_aliases
= (char **)(buffer
+ pos
);
239 pos
+= sizeof(char *);
241 /* copy aliases and fill new pointer list */
242 for (p
= h
->h_aliases
, q
= h_aliases
; *p
!= 0; p
++, q
++)
245 if (size
<= pos
+ len
)
250 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
251 buffer
[pos
+ len
] = '\0';
252 *q
= buffer
+ pos
; /* set copied pointer to copied content */
255 *++q
= 0; /* null terminate the pointer list */
256 h
->h_aliases
= h_aliases
; /* copy pointer to pointers */
260 #endif // HAVE_GETHOSTBYNAME
262 hostent
*wxGethostbyname_r(const char *hostname
,
269 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
270 gethostbyname_r(hostname
, h
, buffer
, size
, &he
, err
);
271 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
272 he
= gethostbyname_r(hostname
, h
, buffer
, size
, err
);
273 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
275 *err
= gethostbyname_r(hostname
, h
, &buffer
);
277 #elif defined(HAVE_GETHOSTBYNAME)
278 wxLOCK_GETBY_MUTEX(name
);
280 he
= gethostbyname(hostname
);
284 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
286 #error "No gethostbyname[_r]()"
292 hostent
*wxGethostbyaddr_r(const char *addr_buf
,
301 #if defined(HAVE_FUNC_GETHOSTBYADDR_R_6)
302 gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, &he
, err
);
303 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_5)
304 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, err
);
305 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_3)
307 *err
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, &buffer
);
309 #elif defined(HAVE_GETHOSTBYADDR)
310 wxLOCK_GETBY_MUTEX(addr
);
312 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
316 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
318 #error "No gethostbyaddr[_r]()"
324 #if defined(HAVE_GETSERVBYNAME)
325 servent
*deepCopyServent(servent
*s
,
330 /* copy plain old structure */
331 memcpy(s
, se
, sizeof(servent
));
334 int len
= strlen(s
->s_name
);
339 memcpy(buffer
, s
->s_name
, len
);
343 /* track position in the buffer */
347 len
= strlen(s
->s_proto
);
348 if (pos
+ len
>= size
)
352 memcpy(buffer
+ pos
, s
->s_proto
, len
);
353 buffer
[pos
+ len
] = '\0';
354 s
->s_proto
= buffer
+ pos
;
356 /* track position in the buffer */
359 /* ensure pointer alignment */
360 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
361 if(misalign
< sizeof(char *))
364 /* leave space for pointer list */
365 char **p
= s
->s_aliases
, **q
;
366 char **s_aliases
= (char **)(buffer
+ pos
);
368 pos
+= sizeof(char *);
370 /* copy addresses and fill new pointer list */
371 for (p
= s
->s_aliases
, q
= s_aliases
; *p
!= 0; p
++, q
++){
373 if (size
<= pos
+ len
)
377 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
378 buffer
[pos
+ len
] = '\0';
379 *q
= buffer
+ pos
; /* set copied pointer to copied content */
382 *++q
= 0; /* null terminate the pointer list */
383 s
->s_aliases
= s_aliases
; /* copy pointer to pointers */
386 #endif // HAVE_GETSERVBYNAME
388 servent
*wxGetservbyname_r(const char *port
,
389 const char *protocol
,
391 wxGetservBuf
& buffer
,
395 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
396 getservbyname_r(port
, protocol
, serv
, buffer
, size
, &se
);
397 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
398 se
= getservbyname_r(port
, protocol
, serv
, buffer
, size
);
399 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
401 if ( getservbyname_r(port
, protocol
, serv
, &buffer
) != 0 )
403 #elif defined(HAVE_GETSERVBYNAME)
404 wxLOCK_GETBY_MUTEX(serv
);
406 se
= getservbyname(port
, protocol
);
408 se
= deepCopyServent(serv
, se
, buffer
, size
);
410 #error "No getservbyname[_r]()"
415 } // anonymous namespace
417 // ============================================================================
418 // wxSockAddressImpl implementation
419 // ============================================================================
421 // FIXME-VC6: helper macros to call Alloc/Get() hiding the ugly dummy argument
422 #define ALLOC(T) Alloc(static_cast<T *>(NULL))
423 #define GET(T) Get(static_cast<T *>(NULL))
425 // ----------------------------------------------------------------------------
426 // INET or INET6 address family
427 // ----------------------------------------------------------------------------
429 wxString
wxSockAddressImpl::GetHostName() const
435 if ( m_family
== FAMILY_INET6
)
437 sockaddr_in6
* const addr6
= GET(sockaddr_in6
);
438 addrbuf
= &addr6
->sin6_addr
;
439 addrbuflen
= sizeof(addr6
->sin6_addr
);
444 sockaddr_in
* const addr
= GET(sockaddr_in
);
448 addrbuf
= &addr
->sin_addr
;
449 addrbuflen
= sizeof(addr
->sin_addr
);
455 if ( !wxGethostbyaddr_r
457 static_cast<const char *>(addrbuf
),
469 return wxString::FromUTF8(he
.h_name
);
472 bool wxSockAddressImpl::SetPortName(const wxString
& name
, const char *protocol
)
474 // test whether it's a number first
476 if ( name
.ToULong(&port
) )
481 else // it's a service name
485 if ( !wxGetservbyname_r(name
.utf8_str(), protocol
, &se
,
486 buffer
, sizeof(buffer
)) )
489 // s_port is in network byte order and SetPort() uses the host byte
490 // order and we prefer to reuse it from here instead of assigning to
492 port
= ntohs(se
.s_port
);
495 return SetPort(port
);
498 // ----------------------------------------------------------------------------
499 // INET address family
500 // ----------------------------------------------------------------------------
502 void wxSockAddressImpl::CreateINET()
504 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
506 m_family
= FAMILY_INET
;
507 sockaddr_in
* const addr
= ALLOC(sockaddr_in
);
508 addr
->sin_family
= FAMILY_INET
;
511 bool wxSockAddressImpl::SetHostName4(const wxString
& name
)
513 sockaddr_in
* const addr
= GET(sockaddr_in
);
517 const wxScopedCharBuffer
namebuf(name
.utf8_str());
519 // first check if this is an address in quad dotted notation
520 #if defined(HAVE_INET_ATON)
521 if ( inet_aton(namebuf
, &addr
->sin_addr
) )
523 #elif defined(HAVE_INET_ADDR)
524 addr
->sin_addr
.s_addr
= inet_addr(namebuf
);
525 if ( addr
->sin_addr
.s_addr
!= INADDR_NONE
)
528 #error "Neither inet_aton() nor inet_addr() is available?"
531 // it's a host name, resolve it
535 if ( !wxGethostbyname_r(namebuf
, &he
, buffer
, sizeof(buffer
), &err
) )
538 addr
->sin_addr
.s_addr
= ((in_addr
*)he
.h_addr
)->s_addr
;
542 bool wxSockAddressImpl::GetHostAddress(wxUint32
*address
) const
544 sockaddr_in
* const addr
= GET(sockaddr_in
);
548 *address
= ntohl(addr
->sin_addr
.s_addr
);
553 bool wxSockAddressImpl::SetHostAddress(wxUint32 address
)
555 sockaddr_in
* const addr
= GET(sockaddr_in
);
559 addr
->sin_addr
.s_addr
= htonl(address
);
564 wxUint16
wxSockAddressImpl::GetPort4() const
566 sockaddr_in
* const addr
= GET(sockaddr_in
);
570 return ntohs(addr
->sin_port
);
573 bool wxSockAddressImpl::SetPort4(wxUint16 port
)
575 sockaddr_in
* const addr
= GET(sockaddr_in
);
579 addr
->sin_port
= htons(port
);
586 // ----------------------------------------------------------------------------
587 // INET6 address family
588 // ----------------------------------------------------------------------------
590 void wxSockAddressImpl::CreateINET6()
592 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
594 m_family
= FAMILY_INET6
;
595 sockaddr_in6
* const addr
= ALLOC(sockaddr_in6
);
596 addr
->sin6_family
= FAMILY_INET6
;
599 bool wxSockAddressImpl::SetHostName6(const wxString
& hostname
)
601 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
606 memset(&hints
, 0, sizeof(hints
));
607 hints
.ai_family
= AF_INET6
;
609 addrinfo
*info
= NULL
;
610 int rc
= getaddrinfo(hostname
.utf8_str(), NULL
, &hints
, &info
);
613 // use gai_strerror()?
617 wxCHECK_MSG( info
, false, "should have info on success" );
619 wxASSERT_MSG( int(info
->ai_addrlen
) == m_len
, "unexpected address length" );
621 memcpy(addr
, info
->ai_addr
, info
->ai_addrlen
);
627 bool wxSockAddressImpl::GetHostAddress(in6_addr
*address
) const
629 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
633 *address
= addr
->sin6_addr
;
638 bool wxSockAddressImpl::SetHostAddress(const in6_addr
& address
)
640 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
644 addr
->sin6_addr
= address
;
649 wxUint16
wxSockAddressImpl::GetPort6() const
651 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
655 return ntohs(addr
->sin6_port
);
658 bool wxSockAddressImpl::SetPort6(wxUint16 port
)
660 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
664 addr
->sin6_port
= htons(port
);
669 bool wxSockAddressImpl::SetToAnyAddress6()
671 static const in6_addr any
= IN6ADDR_ANY_INIT
;
673 return SetHostAddress(any
);
678 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
680 // ----------------------------------------------------------------------------
681 // Unix address family
682 // ----------------------------------------------------------------------------
684 #ifndef UNIX_PATH_MAX
685 #define UNIX_PATH_MAX (WXSIZEOF(((sockaddr_un *)NULL)->sun_path))
688 void wxSockAddressImpl::CreateUnix()
690 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
692 m_family
= FAMILY_UNIX
;
693 sockaddr_un
* const addr
= ALLOC(sockaddr_un
);
694 addr
->sun_family
= FAMILY_UNIX
;
695 addr
->sun_path
[0] = '\0';
698 bool wxSockAddressImpl::SetPath(const wxString
& path
)
700 sockaddr_un
* const addr
= GET(sockaddr_un
);
704 const wxScopedCharBuffer
buf(path
.utf8_str());
705 if ( strlen(buf
) >= UNIX_PATH_MAX
)
708 wxStrlcpy(addr
->sun_path
, buf
, UNIX_PATH_MAX
);
713 wxString
wxSockAddressImpl::GetPath() const
715 sockaddr_un
* const addr
= GET(sockaddr_un
);
719 return wxString::FromUTF8(addr
->sun_path
);
722 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
727 // ----------------------------------------------------------------------------
729 // ----------------------------------------------------------------------------
731 const sockaddr
*wxSockAddress::GetAddressData() const
733 return GetAddress().GetAddr();
736 int wxSockAddress::GetAddressDataLen() const
738 return GetAddress().GetLen();
741 void wxSockAddress::Init()
743 if ( wxIsMainThread() && !wxSocketBase::IsInitialized() )
745 // we must do it before using any socket functions
746 (void)wxSocketBase::Initialize();
750 wxSockAddress::wxSockAddress()
754 m_impl
= new wxSockAddressImpl();
757 wxSockAddress::wxSockAddress(const wxSockAddress
& other
)
762 m_impl
= new wxSockAddressImpl(*other
.m_impl
);
765 wxSockAddress::~wxSockAddress()
770 void wxSockAddress::SetAddress(const wxSockAddressImpl
& address
)
772 if ( &address
!= m_impl
)
775 m_impl
= new wxSockAddressImpl(address
);
779 wxSockAddress
& wxSockAddress::operator=(const wxSockAddress
& addr
)
781 SetAddress(addr
.GetAddress());
786 void wxSockAddress::Clear()
791 // ----------------------------------------------------------------------------
793 // ----------------------------------------------------------------------------
795 wxSockAddressImpl
& wxIPaddress::GetImpl()
797 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
798 m_impl
->CreateINET();
803 bool wxIPaddress::Hostname(const wxString
& name
)
805 wxCHECK_MSG( !name
.empty(), false, "empty host name is invalid" );
807 m_origHostname
= name
;
809 return GetImpl().SetHostName(name
);
812 bool wxIPaddress::Service(const wxString
& name
)
814 return GetImpl().SetPortName(name
, "tcp");
817 bool wxIPaddress::Service(unsigned short port
)
819 return GetImpl().SetPort(port
);
822 bool wxIPaddress::LocalHost()
824 return Hostname("localhost");
827 wxString
wxIPaddress::Hostname() const
829 return GetImpl().GetHostName();
832 unsigned short wxIPaddress::Service() const
834 return GetImpl().GetPort();
837 bool wxIPaddress::operator==(const wxIPaddress
& addr
) const
839 return Hostname().Cmp(addr
.Hostname()) == 0 &&
840 Service() == addr
.Service();
843 bool wxIPaddress::AnyAddress()
845 return GetImpl().SetToAnyAddress();
848 // ----------------------------------------------------------------------------
850 // ----------------------------------------------------------------------------
852 void wxIPV4address::DoInitImpl()
854 m_impl
->CreateINET();
857 bool wxIPV4address::Hostname(unsigned long addr
)
859 if ( !GetImpl().SetHostAddress(addr
) )
861 m_origHostname
.clear();
865 m_origHostname
= Hostname();
869 bool wxIPV4address::IsLocalHost() const
871 return Hostname() == "localhost" || IPAddress() == "127.0.0.1";
874 wxString
wxIPV4address::IPAddress() const
877 if ( !GetImpl().GetHostAddress(&addr
) )
880 return wxString::Format
890 bool wxIPV4address::BroadcastAddress()
892 return GetImpl().SetToBroadcastAddress();
897 // ---------------------------------------------------------------------------
899 // ---------------------------------------------------------------------------
901 void wxIPV6address::DoInitImpl()
903 m_impl
->CreateINET6();
906 bool wxIPV6address::Hostname(unsigned char addr
[16])
908 unsigned short wk
[8];
909 for ( int i
= 0; i
< 8; ++i
)
913 wk
[i
] |= addr
[2*i
+1];
920 "%x:%x:%x:%x:%x:%x:%x:%x",
921 wk
[0], wk
[1], wk
[2], wk
[3], wk
[4], wk
[5], wk
[6], wk
[7]
926 bool wxIPV6address::IsLocalHost() const
928 if ( Hostname() == "localhost" )
931 wxString addr
= IPAddress();
932 return addr
== wxT("::1") ||
933 addr
== wxT("0:0:0:0:0:0:0:1") ||
934 addr
== wxT("::ffff:127.0.0.1");
937 wxString
wxIPV6address::IPAddress() const
945 if ( !GetImpl().GetHostAddress(&u
.addr6
) )
948 const wxUint8
* const addr
= u
.bytes
;
952 prefix_zero_count
= 0;
953 for ( i
= 0; i
< 8; ++i
)
955 words
[i
] = addr
[i
*2];
957 words
[i
] |= addr
[i
*2+1];
958 if ( i
== prefix_zero_count
&& words
[i
] == 0 )
963 if ( prefix_zero_count
== 8 )
965 result
= wxT( "::" );
967 else if ( prefix_zero_count
== 6 && words
[5] == 0xFFFF )
970 result
.Printf("::ffff:%d.%d.%d.%d",
971 addr
[12], addr
[13], addr
[14], addr
[15]);
976 for ( i
= prefix_zero_count
; i
< 8; ++i
)
978 result
+= wxString::Format(":%x", words
[i
]);
987 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
989 // ---------------------------------------------------------------------------
991 // ---------------------------------------------------------------------------
993 wxSockAddressImpl
& wxUNIXaddress::GetUNIX()
995 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
996 m_impl
->CreateUnix();
1001 void wxUNIXaddress::Filename(const wxString
& fname
)
1003 GetUNIX().SetPath(fname
);
1006 wxString
wxUNIXaddress::Filename() const
1008 return GetUNIX().GetPath();
1011 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
1013 #endif // wxUSE_SOCKETS