简体   繁体   中英

Connect a socket on localhost on iOS

In my iOS app, I want to connect a socket on localhost. It works fine on simulator but not on device. I create a socket that listen on 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:

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. 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 ?

Thanks for your help.

EDIT:

It seems that setting the socket option SO_USELOOPBACK solves the problem:

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. For the device you probably need to connect using the IP address of your machine and not 'localhost'/'127.0.0.1'

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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