将IPV4地址作为字符串

时间:2015-08-12 20:49:07

标签: ios objective-c

我正在使用Bonjour浏览特定设备的可用服务。我可以成功获取并解析从浏览返回的服务,但是我想获取服务并以字符串形式检索它的IPV4地址。为此,我使用arpa / inet库将NSNetService.addresses接收的NSdata对象转换为String。下面的代码大部分时间都可以使用,但是下面的行有时会导致应用程序崩溃。

NSString * ipString = [NSString stringWithFormat:@“%s”, INET_NTOA(socketAddress-> sin_addr)];

错误:EXC_BAD_ACCESS

我确信这与我宣布此代码的方式,任何想法有关?

    + (NSString *)getStringFromAddressData:(NSData *)dataIn {
        struct sockaddr_in  *socketAddress = nil;

        socketAddress = (struct sockaddr_in *)[dataIn bytes];
        NSString *ipString = [NSString stringWithFormat: @"%s",      inet_ntoa(socketAddress->sin_addr)];

        return ipString;
    }

堆栈追踪:

    2015-08-13 08:23:45.860 Semiphores[4664:2119558] Stack trace : (
0   Semiphores                          0x0000000100001c0b +[BonjourAddressHelper getStringFromAddressData:] + 107
1   Semiphores                          0x0000000100007c8a _TFFC10Semiphores17BonjourController15resolveServicesFS0_FPSs9AnyObject_T_U_FT_T_ + 2682
2   Semiphores                          0x0000000100007207 _TTRXFo__dT__XFdCb__dT__ + 39
3   libdispatch.dylib                   0x00000001006852bb _dispatch_call_block_and_release + 12
4   libdispatch.dylib                   0x000000010067fd43 _dispatch_client_callout + 8
5   libdispatch.dylib                   0x0000000100683283 _dispatch_root_queue_drain + 1471
6   libdispatch.dylib                   0x0000000100694cd0 _dispatch_worker_thread3 + 106
7   libsystem_pthread.dylib             0x00007fff86770637 _pthread_wqthread + 729
8   libsystem_pthread.dylib             0x00007fff8676e40d start_wqthread + 13

1 个答案:

答案 0 :(得分:0)

如果有人传递了nil数据会怎么样?

   + (NSString *)getStringFromAddressData:(NSData *)dataIn {
        if (dataIn != nil) {
            struct sockaddr_in  *socketAddress = nil;

            socketAddress = (struct sockaddr_in *)[dataIn bytes];
            NSString *ipString = [NSString stringWithFormat: @"%s",    inet_ntoa(socketAddress->sin_addr)];
            return ipString;
        }
        return @"";
    }