繁体   English   中英

iOS开发:从NSReadStream获取私有IP和端口

[英]iOS Development: Get private IP and port from NSReadStream

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

我可以通过迭代设备的接口来获取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;

好的,这对我现在有效。 也许我可以帮助某个来自Google或其他地方的人。

- (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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM