gpt4 book ai didi

objective-c - 如何判断远程网络设备是否可用?

转载 作者:可可西里 更新时间:2023-11-01 02:51:11 25 4
gpt4 key购买 nike

我找到了很多关于如何确定是否的答案,例如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 不会花很长时间来报告网络无法访问...

谢谢,

-皮特

最佳答案

将可达性等级添加到您的项目。

 #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

同时检查:https://developer.apple.com/library/ios/samplecode/Reachability/Listings/Reachability_Reachability_h.html

编辑:同时添加 SystemConfiguration 框架。

关于objective-c - 如何判断远程网络设备是否可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36743050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com