Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify the connection timeout handling for socket creation. #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions src/Socket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,45 @@ public extension SSH {
setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeoutStruct, socklen_t(MemoryLayout<timeval>.size))
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeoutStruct, socklen_t(MemoryLayout<timeval>.size))

if Darwin.connect(sockfd, info.pointee.ai_addr, info.pointee.ai_addrlen) == 0 {
break
// 设置为非阻塞模式进行连接
let flags = fcntl(sockfd, F_GETFL, 0)
guard flags >= 0 else {
Darwin.close(sockfd)
continue
}

Darwin.close(sockfd)
sockfd = -1
_ = fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)

// 非阻塞连接
let connectResult = Darwin.connect(sockfd, info.pointee.ai_addr, info.pointee.ai_addrlen)
if connectResult < 0 && errno == EINPROGRESS {
var writeSet = fd_set()
writeSet.zero()
writeSet.set(sockfd)

let selectResult = Darwin.select(sockfd + 1, nil, &writeSet, nil, &timeoutStruct)
if selectResult <= 0 {
Darwin.close(sockfd)
sockfd = -1
continue
}

// 检查连接是否成功
var error: Int32 = 0
var len = socklen_t(MemoryLayout<Int32>.size)
if getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0 {
Darwin.close(sockfd)
sockfd = -1
continue
}
} else if connectResult < 0 {
Darwin.close(sockfd)
sockfd = -1
continue
}

// 恢复阻塞模式
_ = fcntl(sockfd, F_SETFL, flags)
break
}

return sockfd
Expand Down