@@ -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+
11951215auto 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 {
12351255using namespace pipy ;
12361256
12371257template <> 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;
0 commit comments