]>
git.saurik.com Git - wxWidgets.git/blob - src/common/sckaddr.cpp
67ca3fbcdfa77af4a5a368ad4eb55a98f3d90bac
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"
52 #if defined(__UNIX__) && !defined(__CYGWIN__)
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 #ifndef HAVE_GETHOSTBYNAME
86 #define HAVE_GETHOSTBYNAME
88 #ifndef HAVE_GETSERVBYNAME
89 #define HAVE_GETSERVBYNAME
92 // under MSW getxxxbyname() functions are MT-safe (but not reentrant) so
93 // we don't need to serialize calls to them
94 #define wxHAS_MT_SAFE_GETBY_FUNCS
97 // this header does dynamic dispatching of getaddrinfo/freeaddrinfo()
98 // by implementing them in its own code if the system versions are not
99 // available (as is the case for anything < XP)
101 // NB: if this is not available for the other compilers (so far tested
102 // with MSVC only) we should just use wxDynamicLibrary "manually"
104 // disable a warning occurring in Microsoft own version of this file
105 #pragma warning(disable:4706)
109 #pragma warning(default:4706)
114 // we assume that we have gethostbyaddr_r() if and only if we have
115 // gethostbyname_r() and that it uses the similar conventions to it (see
116 // comment in configure)
117 #define HAVE_GETHOSTBYADDR HAVE_GETHOSTBYNAME
118 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
119 #define HAVE_FUNC_GETHOSTBYADDR_R_3
121 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_5
122 #define HAVE_FUNC_GETHOSTBYADDR_R_5
124 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_6
125 #define HAVE_FUNC_GETHOSTBYADDR_R_6
128 // the _r functions need the extra buffer parameter but unfortunately its type
129 // differs between different systems and for the systems which use opaque
130 // structs for it (at least AIX and OpenBSD) it must be zero-filled before
131 // being passed to the system functions
132 #ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
133 struct wxGethostBuf
: hostent_data
137 memset(this, 0, sizeof(hostent_data
));
141 typedef char wxGethostBuf
[1024];
144 #ifdef HAVE_FUNC_GETSERVBYNAME_R_4
145 struct wxGetservBuf
: servent_data
149 memset(this, 0, sizeof(servent_data
));
153 typedef char wxGetservBuf
[1024];
156 #if defined(wxHAS_MT_SAFE_GETBY_FUNCS) || !wxUSE_THREADS
157 #define wxLOCK_GETBY_MUTEX(name)
158 #else // may need mutexes to protect getxxxbyxxx() calls
159 #if defined(HAVE_GETHOSTBYNAME) || \
160 defined(HAVE_GETHOSTBYADDR) || \
161 defined(HAVE_GETSERVBYNAME)
162 #include "wx/thread.h"
166 // these mutexes are used to serialize
167 wxMutex nameLock
, // gethostbyname()
168 addrLock
, // gethostbyaddr()
169 servLock
; // getservbyname()
172 #define wxLOCK_GETBY_MUTEX(name) wxMutexLocker locker(name ## Lock)
173 #endif // we don't have _r functions
174 #endif // wxUSE_THREADS
179 #if defined(HAVE_GETHOSTBYNAME)
180 hostent
*deepCopyHostent(hostent
*h
,
186 /* copy old structure */
187 memcpy(h
, he
, sizeof(hostent
));
190 int len
= strlen(h
->h_name
);
196 memcpy(buffer
, h
->h_name
, len
);
200 /* track position in the buffer */
203 /* reuse len to store address length */
206 /* ensure pointer alignment */
207 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
208 if(misalign
< sizeof(char *))
211 /* leave space for pointer list */
212 char **p
= h
->h_addr_list
, **q
;
213 char **h_addr_list
= (char **)(buffer
+ pos
);
215 pos
+= sizeof(char *);
217 /* copy addresses and fill new pointer list */
218 for (p
= h
->h_addr_list
, q
= h_addr_list
; *p
!= 0; p
++, q
++)
220 if (size
< pos
+ len
)
225 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
226 *q
= buffer
+ pos
; /* set copied pointer to copied content */
229 *++q
= 0; /* null terminate the pointer list */
230 h
->h_addr_list
= h_addr_list
; /* copy pointer to pointers */
232 /* ensure word alignment of pointers */
233 misalign
= sizeof(char *) - pos%sizeof
(char *);
234 if(misalign
< sizeof(char *))
237 /* leave space for pointer list */
239 char **h_aliases
= (char **)(buffer
+ pos
);
241 pos
+= sizeof(char *);
243 /* copy aliases and fill new pointer list */
244 for (p
= h
->h_aliases
, q
= h_aliases
; *p
!= 0; p
++, q
++)
247 if (size
<= pos
+ len
)
252 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
253 buffer
[pos
+ len
] = '\0';
254 *q
= buffer
+ pos
; /* set copied pointer to copied content */
257 *++q
= 0; /* null terminate the pointer list */
258 h
->h_aliases
= h_aliases
; /* copy pointer to pointers */
262 #endif // HAVE_GETHOSTBYNAME
264 hostent
*wxGethostbyname_r(const char *hostname
,
271 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
272 gethostbyname_r(hostname
, h
, buffer
, size
, &he
, err
);
273 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
274 he
= gethostbyname_r(hostname
, h
, buffer
, size
, err
);
275 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
276 he
= gethostbyname_r(hostname
, h
, &buffer
);
278 #elif defined(HAVE_GETHOSTBYNAME)
279 wxLOCK_GETBY_MUTEX(name
);
281 he
= gethostbyname(hostname
);
285 he
= deepCopyHostent(h
, he
, buffer
, size
, err
);
287 #error "No gethostbyname[_r]()"
293 hostent
*wxGethostbyaddr_r(const char *addr_buf
,
302 #if defined(HAVE_FUNC_GETHOSTBYADDR_R_6)
303 gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, &he
, err
);
304 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_5)
305 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, buffer
, size
, err
);
306 #elif defined(HAVE_FUNC_GETHOSTBYADDR_R_3)
307 he
= 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)
400 if ( getservbyname_r(port
, protocol
, serv
, &buffer
) != 0 )
402 #elif defined(HAVE_GETSERVBYNAME)
403 wxLOCK_GETBY_MUTEX(serv
);
405 se
= getservbyname(port
, protocol
);
407 se
= deepCopyServent(serv
, se
, buffer
, size
);
409 #error "No getservbyname[_r]()"
414 } // anonymous namespace
416 // ============================================================================
417 // wxSockAddressImpl implementation
418 // ============================================================================
420 // FIXME-VC6: helper macros to call Alloc/Get() hiding the ugly dummy argument
421 #define ALLOC(T) Alloc(static_cast<T *>(NULL))
422 #define GET(T) Get(static_cast<T *>(NULL))
424 // ----------------------------------------------------------------------------
425 // INET or INET6 address family
426 // ----------------------------------------------------------------------------
428 wxString
wxSockAddressImpl::GetHostName() const
434 if ( m_family
== FAMILY_INET6
)
436 sockaddr_in6
* const addr6
= GET(sockaddr_in6
);
437 addrbuf
= &addr6
->sin6_addr
;
438 addrbuflen
= sizeof(addr6
->sin6_addr
);
443 sockaddr_in
* const addr
= GET(sockaddr_in
);
447 addrbuf
= &addr
->sin_addr
;
448 addrbuflen
= sizeof(addr
->sin_addr
);
454 if ( !wxGethostbyaddr_r
456 static_cast<const char *>(addrbuf
),
468 return wxString::FromUTF8(he
.h_name
);
471 bool wxSockAddressImpl::SetPortName(const wxString
& name
, const char *protocol
)
473 // test whether it's a number first
475 if ( name
.ToULong(&port
) )
480 else // it's a service name
484 if ( !wxGetservbyname_r(name
.utf8_str(), protocol
, &se
,
485 buffer
, sizeof(buffer
)) )
488 // s_port is in network byte order and SetPort() uses the host byte
489 // order and we prefer to reuse it from here instead of assigning to
491 port
= ntohs(se
.s_port
);
494 return SetPort(port
);
497 // ----------------------------------------------------------------------------
498 // INET address family
499 // ----------------------------------------------------------------------------
501 void wxSockAddressImpl::CreateINET()
503 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
505 m_family
= FAMILY_INET
;
506 sockaddr_in
* const addr
= ALLOC(sockaddr_in
);
507 addr
->sin_family
= FAMILY_INET
;
510 bool wxSockAddressImpl::SetHostName4(const wxString
& name
)
512 sockaddr_in
* const addr
= GET(sockaddr_in
);
516 const wxScopedCharBuffer
namebuf(name
.utf8_str());
518 // first check if this is an address in quad dotted notation
519 #if defined(HAVE_INET_ATON)
520 if ( inet_aton(namebuf
, &addr
->sin_addr
) )
522 #elif defined(HAVE_INET_ADDR)
523 addr
->sin_addr
.s_addr
= inet_addr(namebuf
);
524 if ( addr
->sin_addr
.s_addr
!= INADDR_NONE
)
527 #error "Neither inet_aton() nor inet_addr() is available?"
530 // it's a host name, resolve it
534 if ( !wxGethostbyname_r(namebuf
, &he
, buffer
, sizeof(buffer
), &err
) )
537 addr
->sin_addr
.s_addr
= ((in_addr
*)he
.h_addr
)->s_addr
;
541 bool wxSockAddressImpl::GetHostAddress(wxUint32
*address
) const
543 sockaddr_in
* const addr
= GET(sockaddr_in
);
547 *address
= ntohl(addr
->sin_addr
.s_addr
);
552 bool wxSockAddressImpl::SetHostAddress(wxUint32 address
)
554 sockaddr_in
* const addr
= GET(sockaddr_in
);
558 addr
->sin_addr
.s_addr
= htonl(address
);
563 wxUint16
wxSockAddressImpl::GetPort4() const
565 sockaddr_in
* const addr
= GET(sockaddr_in
);
569 return ntohs(addr
->sin_port
);
572 bool wxSockAddressImpl::SetPort4(wxUint16 port
)
574 sockaddr_in
* const addr
= GET(sockaddr_in
);
578 addr
->sin_port
= htons(port
);
585 // ----------------------------------------------------------------------------
586 // INET6 address family
587 // ----------------------------------------------------------------------------
589 void wxSockAddressImpl::CreateINET6()
591 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
593 m_family
= FAMILY_INET6
;
594 sockaddr_in6
* const addr
= ALLOC(sockaddr_in6
);
595 addr
->sin6_family
= FAMILY_INET6
;
598 bool wxSockAddressImpl::SetHostName6(const wxString
& hostname
)
600 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
605 memset(&hints
, 0, sizeof(hints
));
606 hints
.ai_family
= AF_INET6
;
608 addrinfo
*info
= NULL
;
609 int rc
= getaddrinfo(hostname
.utf8_str(), NULL
, &hints
, &info
);
612 // use gai_strerror()?
616 wxCHECK_MSG( info
, false, "should have info on success" );
618 wxASSERT_MSG( int(info
->ai_addrlen
) == m_len
, "unexpected address length" );
620 memcpy(addr
, info
->ai_addr
, info
->ai_addrlen
);
626 bool wxSockAddressImpl::GetHostAddress(in6_addr
*address
) const
628 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
632 *address
= addr
->sin6_addr
;
637 bool wxSockAddressImpl::SetHostAddress(const in6_addr
& address
)
639 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
643 addr
->sin6_addr
= address
;
648 wxUint16
wxSockAddressImpl::GetPort6() const
650 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
654 return ntohs(addr
->sin6_port
);
657 bool wxSockAddressImpl::SetPort6(wxUint16 port
)
659 sockaddr_in6
* const addr
= GET(sockaddr_in6
);
663 addr
->sin6_port
= htons(port
);
668 bool wxSockAddressImpl::SetToAnyAddress6()
670 static const in6_addr any
= IN6ADDR_ANY_INIT
;
672 return SetHostAddress(any
);
677 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
679 // ----------------------------------------------------------------------------
680 // Unix address family
681 // ----------------------------------------------------------------------------
683 #ifndef UNIX_PATH_MAX
684 #define UNIX_PATH_MAX (WXSIZEOF(((sockaddr_un *)NULL)->sun_path))
687 void wxSockAddressImpl::CreateUnix()
689 wxASSERT_MSG( Is(FAMILY_UNSPEC
), "recreating address as different type?" );
691 m_family
= FAMILY_UNIX
;
692 sockaddr_un
* const addr
= ALLOC(sockaddr_un
);
693 addr
->sun_family
= FAMILY_UNIX
;
694 addr
->sun_path
[0] = '\0';
697 bool wxSockAddressImpl::SetPath(const wxString
& path
)
699 sockaddr_un
* const addr
= GET(sockaddr_un
);
703 const wxScopedCharBuffer
buf(path
.utf8_str());
704 if ( strlen(buf
) >= UNIX_PATH_MAX
)
707 wxStrlcpy(addr
->sun_path
, buf
, UNIX_PATH_MAX
);
712 wxString
wxSockAddressImpl::GetPath() const
714 sockaddr_un
* const addr
= GET(sockaddr_un
);
718 return wxString::FromUTF8(addr
->sun_path
);
721 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
726 // ----------------------------------------------------------------------------
728 // ----------------------------------------------------------------------------
730 const sockaddr
*wxSockAddress::GetAddressData() const
732 return GetAddress().GetAddr();
735 int wxSockAddress::GetAddressDataLen() const
737 return GetAddress().GetLen();
740 void wxSockAddress::Init()
742 if ( wxIsMainThread() && !wxSocketBase::IsInitialized() )
744 // we must do it before using any socket functions
745 (void)wxSocketBase::Initialize();
749 wxSockAddress::wxSockAddress()
753 m_impl
= new wxSockAddressImpl();
756 wxSockAddress::wxSockAddress(const wxSockAddress
& other
)
761 m_impl
= new wxSockAddressImpl(*other
.m_impl
);
764 wxSockAddress::~wxSockAddress()
769 void wxSockAddress::SetAddress(const wxSockAddressImpl
& address
)
771 if ( &address
!= m_impl
)
774 m_impl
= new wxSockAddressImpl(address
);
778 wxSockAddress
& wxSockAddress::operator=(const wxSockAddress
& addr
)
780 SetAddress(addr
.GetAddress());
785 void wxSockAddress::Clear()
790 // ----------------------------------------------------------------------------
792 // ----------------------------------------------------------------------------
794 wxSockAddressImpl
& wxIPaddress::GetImpl()
796 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
797 m_impl
->CreateINET();
802 bool wxIPaddress::Hostname(const wxString
& name
)
804 wxCHECK_MSG( !name
.empty(), false, "empty host name is invalid" );
806 m_origHostname
= name
;
808 return GetImpl().SetHostName(name
);
811 bool wxIPaddress::Service(const wxString
& name
)
813 return GetImpl().SetPortName(name
, "tcp");
816 bool wxIPaddress::Service(unsigned short port
)
818 return GetImpl().SetPort(port
);
821 bool wxIPaddress::LocalHost()
823 return Hostname("localhost");
826 wxString
wxIPaddress::Hostname() const
828 return GetImpl().GetHostName();
831 unsigned short wxIPaddress::Service() const
833 return GetImpl().GetPort();
836 bool wxIPaddress::operator==(const wxIPaddress
& addr
) const
838 return Hostname().Cmp(addr
.Hostname()) == 0 &&
839 Service() == addr
.Service();
842 bool wxIPaddress::AnyAddress()
844 return GetImpl().SetToAnyAddress();
847 // ----------------------------------------------------------------------------
849 // ----------------------------------------------------------------------------
851 void wxIPV4address::DoInitImpl()
853 m_impl
->CreateINET();
856 bool wxIPV4address::Hostname(unsigned long addr
)
858 if ( !GetImpl().SetHostAddress(addr
) )
860 m_origHostname
.clear();
864 m_origHostname
= Hostname();
868 bool wxIPV4address::IsLocalHost() const
870 return Hostname() == "localhost" || IPAddress() == "127.0.0.1";
873 wxString
wxIPV4address::IPAddress() const
876 if ( !GetImpl().GetHostAddress(&addr
) )
879 return wxString::Format
889 bool wxIPV4address::BroadcastAddress()
891 return GetImpl().SetToBroadcastAddress();
896 // ---------------------------------------------------------------------------
898 // ---------------------------------------------------------------------------
900 void wxIPV6address::DoInitImpl()
902 m_impl
->CreateINET6();
905 bool wxIPV6address::Hostname(unsigned char addr
[16])
907 unsigned short wk
[8];
908 for ( int i
= 0; i
< 8; ++i
)
912 wk
[i
] |= addr
[2*i
+1];
919 "%x:%x:%x:%x:%x:%x:%x:%x",
920 wk
[0], wk
[1], wk
[2], wk
[3], wk
[4], wk
[5], wk
[6], wk
[7]
925 bool wxIPV6address::IsLocalHost() const
927 if ( Hostname() == "localhost" )
930 wxString addr
= IPAddress();
931 return addr
== wxT("::1") ||
932 addr
== wxT("0:0:0:0:0:0:0:1") ||
933 addr
== wxT("::ffff:127.0.0.1");
936 wxString
wxIPV6address::IPAddress() const
944 if ( !GetImpl().GetHostAddress(&u
.addr6
) )
947 const wxUint8
* const addr
= u
.bytes
;
951 prefix_zero_count
= 0;
952 for ( i
= 0; i
< 8; ++i
)
954 words
[i
] = addr
[i
*2];
956 words
[i
] |= addr
[i
*2+1];
957 if ( i
== prefix_zero_count
&& words
[i
] == 0 )
962 if ( prefix_zero_count
== 8 )
964 result
= wxT( "::" );
966 else if ( prefix_zero_count
== 6 && words
[5] == 0xFFFF )
969 result
.Printf("::ffff:%d.%d.%d.%d",
970 addr
[12], addr
[13], addr
[14], addr
[15]);
975 for ( i
= prefix_zero_count
; i
< 8; ++i
)
977 result
+= wxString::Format(":%x", words
[i
]);
986 #ifdef wxHAS_UNIX_DOMAIN_SOCKETS
988 // ---------------------------------------------------------------------------
990 // ---------------------------------------------------------------------------
992 wxSockAddressImpl
& wxUNIXaddress::GetUNIX()
994 if ( m_impl
->GetFamily() == wxSockAddressImpl::FAMILY_UNSPEC
)
995 m_impl
->CreateUnix();
1000 void wxUNIXaddress::Filename(const wxString
& fname
)
1002 GetUNIX().SetPath(fname
);
1005 wxString
wxUNIXaddress::Filename() const
1007 return GetUNIX().GetPath();
1010 #endif // wxHAS_UNIX_DOMAIN_SOCKETS
1012 #endif // wxUSE_SOCKETS