9 #include <netinet/in.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <arpa/inet.h>
13 #include <sys/select.h>
20 #define BINDING_REQUEST 0x0001
21 #define BINDING_RESPONSE 0x0101
23 #define MAPPED_ADDRESS 0x0001
26 #define REQUEST_LEN 20
28 #define ID_COOKIE_FIELD htonl(((int) 'a' << 24) + \
36 uint32_t magic_cookie
;
46 struct stun_mapped_addr
{
53 static int stun_test(const char *server_ip
, int server_port
,
61 struct timeval timeout
;
62 struct stun_header
*hdr
, *rhdr
;
63 struct stun_attrib
*attr
;
64 struct stun_mapped_addr
*addr
;
65 struct sockaddr_in saddr
, daddr
;
71 sock
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
73 panic("Cannot obtain socket!\n");
77 memset(&saddr
, 0, sizeof(saddr
));
78 saddr
.sin_family
= PF_INET
;
79 saddr
.sin_port
= htons(tun_port
);
80 saddr
.sin_addr
.s_addr
= INADDR_ANY
;
82 ret
= bind(sock
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
84 panic("Cannot bind udp socket!\n");
87 hdr
= (struct stun_header
*) pkt
;
88 hdr
->type
= htons(BINDING_REQUEST
);
90 hdr
->magic_cookie
= ID_COOKIE_FIELD
;
91 hdr
->transid
[0] = htonl(rand());
92 hdr
->transid
[1] = htonl(rand());
93 hdr
->transid
[2] = htonl(rand());
95 daddr
.sin_family
= PF_INET
;
96 daddr
.sin_port
= htons(server_port
);
97 daddr
.sin_addr
.s_addr
= inet_addr(server_ip
);
99 ret
= sendto(sock
, pkt
, len
, 0, (struct sockaddr
*) &daddr
,
102 printf("Error sending request (%s)!\n", strerror(errno
));
106 timeout
.tv_sec
= TIMEOUT
/ 1000;
107 timeout
.tv_usec
= (TIMEOUT
% 1000) * 1000;
110 FD_SET(sock
, &fdset
);
112 ret
= select(sock
+ 1, &fdset
, NULL
, NULL
, &timeout
);
114 printf("STUN server timeout!\n");
118 memset(rpkt
, 0, sizeof(rpkt
));
119 len
= read(sock
, rpkt
, sizeof(rpkt
));
123 if (len
< REQUEST_LEN
) {
124 printf("Bad STUN response (%s)!\n", strerror(errno
));
128 rhdr
= (struct stun_header
*) rpkt
;
129 if (ntohs(rhdr
->type
) != BINDING_RESPONSE
) {
130 printf("Wrong STUN response type!\n");
134 if (rhdr
->len
== 0) {
135 printf("No attributes in STUN response!\n");
139 if (rhdr
->magic_cookie
!= hdr
->magic_cookie
||
140 rhdr
->transid
[0] != hdr
->transid
[0] ||
141 rhdr
->transid
[1] != hdr
->transid
[1] ||
142 rhdr
->transid
[2] != hdr
->transid
[2]) {
143 printf("Got wrong STUN transaction id!\n");
148 max
= ntohs(rhdr
->len
) + REQUEST_LEN
;
150 while (off
+ 8 < max
) {
151 attr
= (struct stun_attrib
*) (rpkt
+ off
);
152 if (ntohs(attr
->type
) != MAPPED_ADDRESS
)
155 addr
= (struct stun_mapped_addr
*) (rpkt
+ off
+ 4);
156 if (addr
->family
!= 0x1)
159 in
.s_addr
= addr
->ip
;
160 printf("Public mapping %s:%u!\n",
161 inet_ntoa(in
), ntohs(addr
->port
));
165 off
+= ntohs(attr
->len
);
174 int print_stun_probe(char *server
, int sport
, int tport
)
179 printf("STUN on %s:%u\n", server
, sport
);
182 hp
= gethostbyname(server
);
185 address
= inet_ntoa(*(struct in_addr
*) hp
->h_addr_list
[0]);
186 return stun_test(address
, sport
, tport
);