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

Getting the remote socket address #18

Open
mickeyl opened this issue Nov 28, 2021 · 3 comments
Open

Getting the remote socket address #18

mickeyl opened this issue Nov 28, 2021 · 3 comments

Comments

@mickeyl
Copy link

mickeyl commented Nov 28, 2021

Thanks for this great package. I'm using this on Linux.

What's the best way to get the remote socket address after the accept returns?

@OrkhanAlikhanov
Copy link
Member

OrkhanAlikhanov commented Nov 30, 2021

Hey! Sorry for late response.

I think you would that similar to getting port:

/// Returns the local port number to which the socket is bound.
///
/// - Returns: Local port to which the socket is bound.
open func port() throws -> Port {
var address = sockaddr_in()
var len = socklen_t(MemoryLayout.size(ofValue: address))
let ptr = UnsafeMutableRawPointer(&address).assumingMemoryBound(to: sockaddr.self)
try ing { getsockname(fileDescriptor, ptr, &len) }
return Port(address.sin_port.bigEndian)
}
}

Instead of sin_port you would use sin_addr.

It will have some sort of structure that needs to be converted to string. You can use c functions which to do that. Here is and examples:
https://stackoverflow.com/q/1276294/5555803
https://stackoverflow.com/a/5328184/5555803

I am assuming you need the ip address from the accepted socket.

If you still can't get it work, I can help you further.

@mickeyl
Copy link
Author

mickeyl commented Nov 30, 2021

Thanks, here's what I ended up with:

var address = sockaddr_in()
var len = socklen_t(MemoryLayout.size(ofValue: address))
let ptr = UnsafeMutableRawPointer(&address).assumingMemoryBound(to: sockaddr.self)
try ing { getpeername(client.fileDescriptor, ptr, &len) }

var buffer: [CChar] = .init(repeating: 0, count: 100)
let remoteHost: String = buffer.withUnsafeMutableBufferPointer { pointer in
    guard let cString = inet_ntop(AF_INET, &address.sin_addr, pointer.baseAddress, 100) else { return "unknown" }
    return String(cString: cString)
}

Would a remoteHost or peerName function be useful in the library itself?

@OrkhanAlikhanov
Copy link
Member

That's great! remoteAddress would be better I think.

If you are up to something serious, I would suggest looking into apple/swift-nio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants