Skip to content

Commit d0fa08d

Browse files
committed
[api] Added bind() method to Socket object
1 parent 024dbfe commit d0fa08d

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/socket.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,6 +1192,26 @@ void SocketRaw::on_send(Data *data, const std::error_code &ec, std::size_t n) {
11921192
// Socket
11931193
//
11941194

1195+
void Socket::bind(const std::string &ip_port) {
1196+
std::string ip;
1197+
int port;
1198+
if (utils::get_host_port(ip_port, ip, port)) {
1199+
bind(ip, port);
1200+
} else {
1201+
throw std::runtime_error("invalid [ip]:port format");
1202+
}
1203+
}
1204+
1205+
void Socket::bind(const std::string &ip, int port) {
1206+
if (m_fd) {
1207+
tcp::endpoint ep(asio::ip::make_address(ip), port);
1208+
auto addr = ep.data();
1209+
::bind(m_fd, addr, sizeof(addr));
1210+
} else {
1211+
throw std::runtime_error("socket is gone");
1212+
}
1213+
}
1214+
11951215
auto Socket::get_raw_option(int level, int option, Data *data) -> int {
11961216
if (!m_fd) throw std::runtime_error("socket is gone");
11971217
char buf[1000];
@@ -1235,6 +1255,22 @@ namespace pjs {
12351255
using namespace pipy;
12361256

12371257
template<> void ClassDef<Socket>::init() {
1258+
method("bind", [](Context &ctx, Object *obj, Value &ret) {
1259+
Str *ip;
1260+
int port;
1261+
try {
1262+
if (ctx.argc() > 1) {
1263+
if (!ctx.arguments(2, &ip, &port)) return;
1264+
obj->as<Socket>()->bind(ip->str(), port);
1265+
} else {
1266+
if (!ctx.arguments(1, &ip)) return;
1267+
obj->as<Socket>()->bind(ip->str());
1268+
}
1269+
} catch (std::runtime_error &err) {
1270+
ctx.error(err);
1271+
}
1272+
});
1273+
12381274
method("getRawOption", [](Context &ctx, Object *obj, Value &ret) {
12391275
int level, option;
12401276
pipy::Data *data;

src/socket.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,8 @@ class SocketRaw :
459459

460460
class Socket : public pjs::ObjectTemplate<Socket> {
461461
public:
462+
void bind(const std::string &ip_port);
463+
void bind(const std::string &ip, int port);
462464
auto get_raw_option(int level, int option, Data *data) -> int;
463465
auto set_raw_option(int level, int option, Data *data) -> int;
464466
auto io_control(int64_t op, const Data &input, Data *output = nullptr) -> int;

0 commit comments

Comments
 (0)