简体   繁体   English

在iOS上的localhost上连接套接字

[英]Connect a socket on localhost on iOS

In my iOS app, I want to connect a socket on localhost. 在我的iOS应用程序中,我想在localhost上连接套接字。 It works fine on simulator but not on device. 它在模拟器上工作正常但在设备上没有。 I create a socket that listen on localhost: 我创建一个侦听localhost的套接字:

// create local socket 
SOCKET newSocket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in localaddr;
localaddr.sin_family = AF_INET; 
localaddr.sin_addr.s_addr = htonl(INADDR_ANY);    
localaddr.sin_port = htons(8080);
if (bind(newSocket, (struct sockaddr*)&localaddr, sizeof(localaddr)) != 0)
{    
    NSLog(@"bind main socket failed: %s", strerror(errno));
    return INVALID_SOCKET;
}
if(listen(newSocket, MAX_PENDING_SOCKETS) != 0)
{
    NSLog(@"listen main socket failed: %s", strerror(errno));
    return INVALID_SOCKET;
}

In another part of my app, I create another socket and try to connect it on localhost: 在我的应用程序的另一部分,我创建另一个套接字并尝试在localhost上连接它:

SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in remoteaddr = {0};
remoteaddr.sin_family = AF_INET; 
remoteaddr.sin_addr.s_addr = inet_addr("127.0.0.1");   
remoteaddr.sin_port = htons(8080);     

int error = connect(sock, (struct sockaddr*)&remoteaddr, sizeof(remoteaddr));

This code works fine on Simulator. 此代码在Simulator上正常工作。 But on device I get an error on the connect: "No such file or directory". 但是在设备上我在连接上遇到错误:“没有这样的文件或目录”。

Is this code not correct ? 这段代码不正确吗? Or is it a limitation of iOS ? 或者它是iOS的限制?

Thanks for your help. 谢谢你的帮助。

EDIT: 编辑:

It seems that setting the socket option SO_USELOOPBACK solves the problem: 似乎设置套接字选项SO_USELOOPBACK解决了这个问题:

int sockopt=1;
if(setsockopt(sock, SOL_SOCKET, SO_USELOOPBACK, (char*)&sockopt, sizeof(sockopt)))
    NSLog(@"error on setsockopt SO_USELOOPBACK: %s", strerror(errno));

The simulator runs on the same machine (localhost), but not the device. 模拟器在同一台机器(localhost)上运行,但不在设备上运行。 For the device you probably need to connect using the IP address of your machine and not 'localhost'/'127.0.0.1' 对于设备,您可能需要使用计算机的IP地址进行连接,而不是“localhost”/“127.0.0.1”

Hope that helps. 希望有所帮助。

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

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