I am making an app with two components, an iPhone component and a Mac component. They are supposed to communicate with each other via bonjour. I use the following code on the Mac end to find a port for the service:
NSSocketPort *socket = [[NSSocketPort alloc] init];
struct sockaddr *addr = (struct sockaddr *)[[socket address] bytes];
int port = 9876;
if(addr->sa_family == AF_INET) {
port = ntohs(((struct sockaddr_in *)addr)->sin_port);
} else if(addr->sa_family == AF_INET6) {
port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
} else {
[socket release];
socket = nil;
NSLog(@"The family is neither IPv4 nor IPv6. Can't handle!!!");
}
I can also use this code on the iPhone end and run the app in the simulator, and the connection works fine. However, when I tried to run this code on an actual iPhone, I discovered that NSSocketPort is not available on the iPhone. When I try to start the service with the port 9876, the Mac app displays a connection refused error when I try to connect with it. So how can I find a port to use without using NSSocketPort?
Ok I looked at Apple’s WiTap code and slightly modified it to write myself a method for getting a port:
I took out a lot of the error stuff so it’s probably not optimal, but it works.