BlueSocket icon indicating copy to clipboard operation
BlueSocket copied to clipboard

Get local IP address

Open grill2010 opened this issue 3 years ago • 1 comments

Is is somehow possible with this library to get the local IP address to which the socket is currently bound? E.g. I have following Android Java code which I need to translate to Swift

private static InetAddress getOutboundAddress(SocketAddress remoteAddress) {
        InetAddress localAddress = null;
        try {
            DatagramSocket sock = new DatagramSocket();
            // connect is needed to bind the socket and retrieve the local address later (it would return 0.0.0.0 otherwise)
            sock.connect(remoteAddress);
            localAddress = sock.getLocalAddress();

            sock.disconnect();
            sock.close();
        } catch (Exception e) {
            // ignore
        }

        return localAddress;
}

is there a way which is similar to localAddress = sock.getLocalAddress();?

grill2010 avatar Feb 23 '22 23:02 grill2010

I think I found a way. I don't think there is another way of how you can get the local bound IP address, if there is please let me know. This is the solution I use currently

private static func getOutboundAddress(hostname: String, port: Int32) -> String {
        var tmpDatagramSocket: Socket?
        defer {
            tmpDatagramSocket?.close()
        }
        
        var result: String = ""
        do {
            tmpDatagramSocket = try Socket.create(family: .inet, type: .datagram, proto: .udp)
            try tmpDatagramSocket!.connect(to: hostname, port: port)
            
            var addr_in = sockaddr_in()
            addr_in.sin_len = UInt8(MemoryLayout.size(ofValue: addr_in))
            addr_in.sin_family = sa_family_t(AF_INET)
            var len = socklen_t(addr_in.sin_len)
            
            _ = withUnsafeMutablePointer(to: &addr_in, {
                $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                    getsockname(tmpDatagramSocket!.socketfd, $0, &len)
                }
            })
            
            let address = Socket.Address.ipv4(addr_in)
            if let hostNameAndPort = Socket.hostnameAndPort(from: address) {
                result = hostNameAndPort.hostname
            }
        } catch {
            // ignore
        }
        return result
}

Maybe this could be added to the library in some way so that a bound address can be accessed easier?

grill2010 avatar Feb 24 '22 00:02 grill2010