-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInetAddress.cpp
More file actions
38 lines (32 loc) · 964 Bytes
/
Copy pathInetAddress.cpp
File metadata and controls
38 lines (32 loc) · 964 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "InetAddress.h"
#include <strings.h>
#include <string.h>
InetAddress::InetAddress(uint16_t port, std::string ip) {
bzero(&addr_, sizeof(addr_));
addr_.sin_family = AF_INET;
addr_.sin_port = htons(port);
addr_.sin_addr.s_addr = inet_addr(ip.c_str());
}
std::string InetAddress::toIp() const {
char buf[64] = {0};
// 从addr将address的网络字节序转换为本地字节序
::inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof(buf));
return buf;
}
std::string InetAddress::toIpPort() const {
char buf[64] = {0};
::inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof(buf));
size_t end = strlen(buf);
uint16_t port = ntohs(addr_.sin_port);
sprintf(buf+end, ":%u", port);
return buf;
}
uint16_t InetAddress::toPort() const {
return ntohs(addr_.sin_port);
}
// #include <iostream>
// int main() {
// InetAddress addr(8080);
// std::cout << addr.toIpPort() << std::endl;
// return 0;
// }