Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/test/799.cpp
4128 views
1
// Copyright 2013 The Emscripten Authors. All rights reserved.
2
// Emscripten is available under two separate licenses, the MIT license and the
3
// University of Illinois/NCSA Open Source License. Both these licenses can be
4
// found in the LICENSE file.
5
6
#include <netdb.h>
7
#include <stdint.h>
8
#include <string.h>
9
#include <assert.h>
10
#include <stdio.h>
11
#include <sys/socket.h>
12
#include <netinet/in.h>
13
14
#ifdef __EMSCRIPTEN__
15
#include <arpa/inet.h>
16
#endif
17
18
#define uint16 uint16_t
19
20
class NetworkAddress {
21
private:
22
sockaddr_storage address; ///< The resolved address
23
public:
24
25
/**
26
* Create a network address based on a unresolved host and port
27
* @param hostname the unresolved hostname
28
* @param port the port
29
* @param family the address family
30
*/
31
NetworkAddress(const char *hostname = "", uint16 port = 0, int family = AF_UNSPEC)
32
{
33
memset(&this->address, 0, sizeof(this->address));
34
this->address.ss_family = family;
35
this->SetPort(port);
36
}
37
38
uint16 GetPort() const;
39
void SetPort(uint16 port);
40
};
41
42
/**
43
* Get the port.
44
* @return the port.
45
*/
46
uint16 NetworkAddress::GetPort() const
47
{
48
printf("Get PORT family: %d\n", this->address.ss_family);
49
switch (this->address.ss_family) {
50
case AF_UNSPEC:
51
case AF_INET:
52
return ntohs(((const struct sockaddr_in *)&this->address)->sin_port);
53
54
case AF_INET6:
55
return ntohs(((const struct sockaddr_in6 *)&this->address)->sin6_port);
56
57
default:
58
throw 0;
59
}
60
}
61
62
/**
63
* Set the port.
64
* @param port set the port number.
65
*/
66
void NetworkAddress::SetPort(uint16 port)
67
{
68
printf("Set PORT family: %d, port: %d\n", this->address.ss_family, port);
69
switch (this->address.ss_family) {
70
case AF_UNSPEC:
71
case AF_INET:
72
((struct sockaddr_in*)&this->address)->sin_port = htons(port);
73
break;
74
75
case AF_INET6:
76
((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
77
break;
78
79
default:
80
throw 0;
81
}
82
}
83
84
int main() {
85
NetworkAddress na("127.0.0.1", 3979);
86
printf("PORT: %d\n", na.GetPort());
87
return 0;
88
}
89
90