iOS 开发 : Get private IP and port from NSReadStream

标签 ios sockets nsstream cfsocket

我正在为 iOS 开发一个应用程序。在我的应用程序中,有一个到服务器的工作 TCP 连接,通过 NSStreams 实现。现在我需要连接正在使用的端口,它会产生一些问题。

我可以通过遍历设备接口(interface)获取 IP,但对于端口号,我必须从套接字获取信息。在下面的代码中,我尝试从我的工作中获取套接字并打开 NSInputStream _readstream。问题是,CFSocketCopyAddress 为 nil,我不明白为什么。其他人可以吗?

非常感谢任何帮助!

// Initializing some variables we need
CFSocketContext context;
memset(&context, 0, sizeof(context));
context.info = (__bridge void*)self;
NSString *property = @"kCFStreamPropertySocketNativeHandle";

// Get hands on the used socket via the socket native handle
CFSocketNativeHandle *socketNativeHandle = (CFSocketNativeHandle*)CFReadStreamCopyProperty((__bridge CFReadStreamRef)(_readStream), (__bridge CFStringRef)(property));
CFSocketRef cfSocket = CFSocketCreateWithNative(NULL, *socketNativeHandle, kCFSocketNoCallBack, nil, &context);

// Ask the socket for the address information
CFDataRef               dataRef = CFSocketCopyAddress(cfSocket);                        // dataRef is always nil :(
struct sockaddr_in      *sockaddr = (struct sockaddr_in*)CFDataGetBytePtr(dataRef);

int portnumber = sockaddr->sin_port;

最佳答案

好的,这现在对我有用了。也许我可以帮助来自谷歌或其他地方的人....

- (NSNumber*) getPortnumber{
    int             port        = -1;

    CFSocketContext context;
    memset(&context, 0, sizeof(context));
    context.info = (__bridge void*)self;

    // Get Socket native handle from existing stream
    CFDataRef socketData = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)(_writeStream), kCFStreamPropertySocketNativeHandle);

    // Get the native handle
    CFSocketNativeHandle handle;
    CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), &handle);

    // Get the socket
    CFSocketRef cfSocket = CFSocketCreateWithNative(NULL, handle, kCFSocketNoCallBack, nil, &context);

    // CFSocketCopyAddress will return the address of the socket
    CFDataRef               dataRef = CFSocketCopyAddress(cfSocket);
    struct sockaddr_in      *sockaddr = (struct sockaddr_in*)CFDataGetBytePtr(dataRef);

    // Get the port from the address information
    port = sockaddr->sin_port;

    // Output Objective-C friendly =)
    NSNumber *portnr = [NSNumber numberWithInt:port];
    return portnr;
}

关于iOS 开发 : Get private IP and port from NSReadStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21142549/

相关文章:

ios - NSinputstream 读取数据返回空值?

ios - 无法在单个 UIViewController 中隐藏状态栏

javascript - 如何通过 angularjs 服务正确重新连接到套接字?

客户端服务器与套接字C的基本通信

iphone - iOS - 从服务器接收二进制数据仅适用于 Debug模式

iphone - 锁定 iPhone 仅在 iOS 5 上断开套接字

iphone - 如何在 PhoneGap 中创建 viewController 以与主视图一起使用

ios - 在 UITextView 中获取当前输入的单词

ios - 如何在重新启动应用程序后恢复 AVAssetDownloadTask

sockets - 是否有用于实时通信(websocket或ajax轮询等)的基准?