Determining IP Address from URL in iOS

有些话、适合烂在心里 提交于 2019-12-12 07:16:38

问题


I need to get the IP address of a CDN from it's URL in an iOS app. From a long stack search, i've determined a method for doing this with the following:

struct hostent *host_entry = gethostbyname("stackoverflow.com");
char *buff;
buff = inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));
// buff is now equal to the IP of the stackoverflow.com server

However, when using this code snippet, my app fails to compile and presents this warning: "dereferencing pointer to incomplete type"

I have no knowledge of structs and I do not know how to fix this. Any suggestions?

I also tried:

#include <ifaddrs.h>
#include <arpa/inet.h>

But the result is the same warning.


回答1:


I had no problems compiling that code with the following includes:

#import <netdb.h>
#include <arpa/inet.h>



回答2:


Maybe this function will work?

#import <netdb.h>
#include <arpa/inet.h>

- (NSString*)lookupHostIPAddressForURL:(NSURL*)url
{
    // Ask the unix subsytem to query the DNS
    struct hostent *remoteHostEnt = gethostbyname([[url host] UTF8String]);
    // Get address info from host entry
    struct in_addr *remoteInAddr = (struct in_addr *) remoteHostEnt->h_addr_list[0];
    // Convert numeric addr to ASCII string
    char *sRemoteInAddr = inet_ntoa(*remoteInAddr);
    // hostIP
    NSString* hostIP = [NSString stringWithUTF8String:sRemoteInAddr];
    return hostIP;
}



回答3:


Here is a Swift 3.1 version of converting a URL hostname to IP address.

import Foundation
private func urlToIP(_ url:URL) -> String? {
  guard let hostname = url.host else {
    return nil
  }

  guard let host = hostname.withCString({gethostbyname($0)}) else {
    return nil
  }

  guard host.pointee.h_length > 0 else {
    return nil
  }

  var addr = in_addr()
  memcpy(&addr.s_addr, host.pointee.h_addr_list[0], Int(host.pointee.h_length))

  guard let remoteIPAsC = inet_ntoa(addr) else {
    return nil
  }

  return String.init(cString: remoteIPAsC)
}


来源:https://stackoverflow.com/questions/17726738/determining-ip-address-from-url-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!