我找到了很多关于如何确定例如iPhone连接到互联网,但是找不到确定特定远程网络设备是否可用的解决方案。
我一直在使用这个解决方案,但它并不是那么好:
-(bool)isNetworkDeviceAvailable{
bool ok = true;
const char *servIP = [[txtIPAddress stringValue] UTF8String];
in_port_t servPort = 5001;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock < 0){
NSLog(@"setDAC: Socket creation failed\n");
ok = false;
}
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
if(ok){
if(rtnVal == 0){
NSLog(@"setDAC: inet_pton() failed: invalid address string\n");
ok = false;
}
else if (rtnVal < 0){
NSLog(@"setDAC: inet_pton() failed\n");
ok = false;
}
servAddr.sin_port = htons(servPort);
}
if(ok) if(connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0){
NSLog(@"setDAC: connection failed\n");
ok = false;
}
if(ok){
FILE *datastream = fdopen(sock, "r+");
fclose(datastream);
[lblUnavailable setHidden:YES];
}
else [lblUnavailable setHidden:NO];
return ok;
}
它可以工作,但是在报告无法访问的设备之前,应用程序会挂起一分钟。我确信必须有一个更聪明的方法,因为ping不需要很长时间来报告网络不可访问...
谢谢,
-Pete
答案 0 :(得分:1)
将可达性类添加到项目中。
#import "Reachability.h"
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.example.com"];
NetworkStatus reachabilitytoHost = [reachability currentReachabilityStatus];
if(reachabilitytoHost != NotReachable)
{
//reachable
}
else
{
// not reachable
}
从https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
下载示例编辑:还添加SystemConfiguration
框架。