Socket.swift
Socket.swift copied to clipboard
Getting the remote socket address
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?
Hey! Sorry for late response.
I think you would that similar to getting port:
https://github.com/BiAtoms/Socket.swift/blob/36911c13adfe12859ed43dcba878052b1897fcd3/Sources/Socket.swift#L196-L208
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.
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?
That's great! remoteAddress
would be better I think.
If you are up to something serious, I would suggest looking into apple/swift-nio