Eri*_*tto 5 cocoa objective-c ip-address nshost
我正在尝试使用IP地址NSHost.使用该NSHost对象,我可以使用addresses方法访问对象数组,其中一个对象是IP地址.我担心IP地址可能会改变阵列中从一台机器到另一台机器的位置.有没有办法以通用的方式访问这些信息?
试图在之前的帖子中回答这个问题,但是你可以看到它不足.
这是我的代码:
+(NSString *) ipAddress {
NSHost * h = [[[NSHost currentHost] addresses] objectAtIndex:1];
return h ;
}
Run Code Online (Sandbox Code Playgroud)
mar*_*nte 11
我唯一能想到的是使用类似" http://www.dyndns.org/cgi-bin/check_ip.cgi "的东西,其他人可能会有更好的方法.
这是一个例子,(即快速拼凑的代码)
NSUInteger an_Integer;
NSArray * ipItemsArray;
NSString *externalIP;
NSURL *iPURL = [NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"];
if (iPURL) {
NSError *error = nil;
NSString *theIpHtml = [NSString stringWithContentsOfURL:iPURL
encoding:NSUTF8StringEncoding
error:&error];
if (!error) {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:theIpHtml];
while ([theScanner isAtEnd] == NO) {
// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
[ NSString stringWithFormat:@"%@>", text]
withString:@" "] ;
ipItemsArray =[theIpHtml componentsSeparatedByString:@" "];
an_Integer=[ipItemsArray indexOfObject:@"Address:"];
externalIP =[ipItemsArray objectAtIndex: ++an_Integer];
}
NSLog(@"%@",externalIP);
} else {
NSLog(@"Oops... g %d, %@",
[error code],
[error localizedDescription]);
}
}
[pool drain];
return 0;}
Run Code Online (Sandbox Code Playgroud)
我已经在许多机器上使用它而没有任何问题.
-(void) getIPWithNSHost{
NSArray *addresses = [[NSHost currentHost] addresses];
for (NSString *anAddress in addresses) {
if (![anAddress hasPrefix:@"127"] && [[anAddress componentsSeparatedByString:@"."] count] == 4) {
stringAddress = anAddress;
break;
} else {
stringAddress = @"IPv4 address not available" ;
}
}
//NSLog (@"getIPWithNSHost: stringAddress = %@ ",stringAddress);
}
Run Code Online (Sandbox Code Playgroud)
NSString*stringAddress; 在其他地方宣布
| 归档时间: |
|
| 查看次数: |
14282 次 |
| 最近记录: |