使用 CFStreamCreatePairWithSocketToHost 建立 IPV6 套接字连接

Establishing IPV6 socket connection using CFStreamCreatePairWithSocketToHost

我在使用 CFStreamCreatePairWithSocketToHost 创建与 iPV6 的套接字连接时遇到问题。 但是我能够为相同的端口号创建与 IPV4 的套接字连接。

尝试了所有场景,例如添加 http、不带 http 的 https、在 IPV6 地址之间添加、 对我没有任何作用。

IPV6 的输出是 流事件 8(错误代码为 8) 在 handleEvent 方法中以 NSStreamEventErrorOccurred 结束 下面是代码,我用来创建套接字连接

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
NSString *url = [@"[fe80::fe15:b4ff:feb7:102a]" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *url = @"13.61.14.130";
NSURL *myUrl = [NSURL URLWithString:url];

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)myUrl.path, 82, &readStream, &writeStream);

inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];




-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

    NSLog(@"stream event %i", streamEvent);
    [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%u",streamEvent] message:[NSString stringWithFormat:@"stream event %i", streamEvent] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            break;
        case NSStreamEventHasBytesAvailable:

            if (theStream == inputStream) {

                uint8_t buffer[1024];
                int len;

                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {

                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                        if (nil != output) {

                            NSLog(@"server said: %@", output);
                            [self messageReceived:output];

                        }
                    }
                }
            }
            break;


        case NSStreamEventErrorOccurred:

            NSLog(@"Can not connect to the host!");
            break;

        case NSStreamEventEndEncountered:

            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [theStream release];
            theStream = nil;

            break;
        default:
            NSLog(@"Unknown event");
    }

}

尝试删除 IPV6 之前的 [] 并使用此格式:

NSString *url = [@"fe80::fe15:b4ff:feb7:102a" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

希望这能奏效。