forked from S1mpleBug/muduo_cpp11
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InetAddress.cc
45 lines (39 loc) · 960 Bytes
/
InetAddress.cc
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
39
40
41
42
43
44
45
#include <strings.h>
#include <string.h>
#include "InetAddress.h"
InetAddress::InetAddress(uint16_t port, std::string ip)
{
::memset(&addr_, 0, 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
{
// addr_
char buf[64] = {0};
::inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof buf);
return buf;
}
std::string InetAddress::toIpPort() const
{
// ip:port
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);
}
#if 0
#include <iostream>
int main()
{
InetAddress addr(8080);
std::cout << addr.toIpPort() << std::endl;
}
#endif