Socket.swift icon indicating copy to clipboard operation
Socket.swift copied to clipboard

Getting the remote socket address

Open mickeyl opened this issue 3 years ago • 3 comments

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?

mickeyl avatar Nov 28 '21 16:11 mickeyl

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.

OrkhanAlikhanov avatar Nov 30 '21 10:11 OrkhanAlikhanov

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?

mickeyl avatar Nov 30 '21 13:11 mickeyl

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

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

OrkhanAlikhanov avatar Dec 01 '21 18:12 OrkhanAlikhanov