MCPcopy Create free account
hub / github.com/Oneflow-Inc/oneflow / FindFreePort

Function FindFreePort

oneflow/api/cpp/env_impl.cpp:64–91  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

62}
63
64int32_t FindFreePort(const std::string& addr) {
65#ifdef __linux__
66 int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
67 CHECK_GE(sock, 0) << "fail to find a free port.";
68 int optval = 1;
69 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
70
71 std::mt19937 rng;
72 rng.seed(std::random_device()());
73 std::uniform_int_distribution<std::mt19937::result_type> dist(1, 1000);
74
75 int count = 0;
76 int num_attempts = 200;
77 do {
78 int port = 5000 + dist(rng);
79 struct sockaddr_in sockaddr {};
80 memset(&sockaddr, 0, sizeof(sockaddr));
81 sockaddr.sin_family = AF_INET;
82 sockaddr.sin_port = htons(port);
83 sockaddr.sin_addr.s_addr = inet_addr(addr.c_str());
84 int error = bind(sock, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
85 if (error == 0) { return port; }
86 ++count;
87 } while (count < num_attempts);
88 CHECK_NE(count, num_attempts) << "fail to find a free port.";
89#endif // __linux__
90 return -1;
91}
92
93void CompleteEnvProto(of::EnvProto& env_proto) {
94 auto bootstrap_conf = env_proto.mutable_ctrl_bootstrap_conf();

Callers 1

CompleteEnvProtoFunction · 0.85

Calls 3

random_deviceClass · 0.85
bindFunction · 0.85
seedMethod · 0.45

Tested by

no test coverage detected