"Fossies" - the Fresh Open Source Software Archive 
Member "postal-0.76/address.cpp" (14 Jan 2012, 2322 Bytes) of package /linux/privat/postal-0.76.tgz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style:
standard) with prefixed line numbers and
code folding option.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "address.cpp" see the
Fossies "Dox" file reference documentation.
1 #include "address.h"
2 #include <cstring>
3 #include <stdio.h>
4 #include <cstdlib>
5 #include <netdb.h>
6 #include <sys/socket.h>
7
8 typedef char *PCHAR;
9
10 address::address(const char *addr, unsigned short default_port)
11 {
12 unsigned short port = default_port;
13 char *addr_copy = strdup(addr);
14 int len = strlen(addr);
15 m_count = 1;
16 int i;
17 for(i = 0; i < len; i++)
18 {
19 if(addr_copy[i] == ',')
20 m_count++;
21 }
22 char **names = (char **)malloc(m_count * sizeof(char *));
23 int ind = 0;
24 for(i = 0; i < m_count; i++)
25 {
26 names[i] = &addr_copy[ind];
27 while(addr_copy[ind] && addr_copy[ind] != ',')
28 ind++;
29 addr_copy[ind] = '\0';
30 ind++;
31 }
32 m_rr_dns = (bool *)malloc(m_count * sizeof(bool));
33 m_addr = (sockaddr_in *)malloc(m_count * sizeof(sockaddr_in));
34 m_hostname = (char **)malloc(m_count * sizeof(char *));
35 for(i = 0; i < m_count; i++)
36 {
37 char *hostname = names[i];
38 if(hostname[0] == '+')
39 {
40 m_rr_dns[i] = true;
41 hostname++;
42 }
43 else
44 {
45 m_rr_dns[i] = false;
46 }
47 if(hostname[0] == '[')
48 {
49 hostname++;
50 int j;
51 for(j = 0; hostname[j] && hostname[j] != ']'; j++)
52 {}
53
54 if(!hostname[j])
55 {
56 fprintf(stderr, "Bad address: %s\n", addr);
57 exit(1);
58 }
59 hostname[j] = '\0';
60 port = atoi(&hostname[j + 1]);
61 }
62 m_hostname[i] = strdup(hostname);
63 m_addr[i].sin_family = AF_INET;
64 m_addr[i].sin_port = htons(port);
65 if(!m_rr_dns[i])
66 {
67 if(resolve_name(i))
68 exit(1);
69 }
70 }
71 free(names);
72 free(addr_copy);
73 }
74
75 address::~address()
76 {
77 for(int i = 0; i < m_count; i++)
78 free(m_hostname[i]);
79 free(m_hostname);
80 free(m_rr_dns);
81 free(m_addr);
82 }
83
84 int address::resolve_name(int ind)
85 {
86 hostent *he = gethostbyname(m_hostname[ind]);
87 if(!he)
88 {
89 fprintf(stderr, "Bad address \"%s\" for server.\n", m_hostname[ind]);
90 return 1;
91 }
92 m_addr[ind].sin_addr.s_addr = *((unsigned int *)he->h_addr_list[0]);
93 return 0;
94 }
95
96 sockaddr *address::get_rand_addr()
97 {
98 int ind = 0;
99 if(m_count > 1)
100 ind = rand() % m_count;
101 return get_addr(ind);
102 }
103
104 sockaddr *address::get_addr(int ind)
105 {
106 if(ind < 0 || ind > m_count)
107 return get_rand_addr();
108 if(m_rr_dns[ind])
109 {
110 if(resolve_name(ind))
111 return NULL;
112 }
113 return (sockaddr *)&m_addr[ind];
114 }