iOS development iphone to get the network card address and IP address

Source: Internet
Author: User
Tags get ip sin

Get IP address by domain name

+ (NSString *) Ipadressfromdomain: (NSString *) host

{

Structhostent *hostent = gethostbyname ([hostutf8string]);

if (!hostent) {

Herror ("Resolv");

Returnnull;

}

Structin_addr **list = (STRUCTIN_ADDR * *) hostent->h_addr_list;

NSString *addressstring = [Nsstringstringwithcstring:inet_ntoa (*list[0]) encoding:nsutf8stringencoding];

return addressstring;

}



Get native IP address

+ (NSString *) getipaddress: (BOOL) preferIPv4

{

/*

* Here you can choose whether to return the WiFi first or the cell, or the IPv4 or the IPv6

*/

Nsarray *searcharray = preferIPv4?

@[ios_wifi @ "/" Ip_addr_ipv4, ios_wifi@ "/" Ip_addr_ipv6,ios_cellular @ "/" Ip_addr_ipv4, ios_cellular@ "/" IP_ADDR_IPv6] :

@[ios_wifi @ "/" Ip_addr_ipv6, ios_wifi@ "/" Ip_addr_ipv4,ios_cellular @ "/" Ip_addr_ipv6, ios_cellular@ "/" IP_ADDR_IPv4] ;

Nsdictionary *addresses = [selfgetipaddresses];

NSLog (@ "addresses:%@", addresses);

__blocknsstring *address;

[Searcharray enumerateobjectsusingblock:^ (nsstring *key,nsuinteger idx, BOOL *stop)

{

address = Addresses[key];

if (address) *stop =yes;

} ];

Return address? Address: @ "0.0.0.0";

}


+ (Nsdictionary *) getipaddresses

{

Nsmutabledictionary *addresses = [Nsmutabledictionarydictionarywithcapacity:8];

Retrieve the current Interfaces-returns 0 on success

Structifaddrs *interfaces;

if (!getifaddrs (&interfaces)) {

Loop through linked list of interfaces

Structifaddrs *interface;

for (interface=interfaces; interface; interface=interface->ifa_next) {

if (!) ( Interface->ifa_flags &iff_up)/* | | (Interface->ifa_flags & Iff_loopback) * () {

continue;//deeply nested code harder to read

}

Conststruct sockaddr_in *addr = (conststruct sockaddr_in*) interface->ifa_addr;

Char Addrbuf[max (Inet_addrstrlen,inet6_addrstrlen)];

if (addr && (addr->sin_family==af_inet | | addr->sin_family==af_inet6)) {

NSString *name = [nsstringstringwithutf8string:interface->ifa_name];

NSString *type =nil;

if (addr->sin_family ==af_inet) {

if (Inet_ntop (Af_inet, &addr->sin_addr, Addrbuf, Inet_addrstrlen)) {

Type = Ip_addr_ipv4;

}

} else {

Conststruct sockaddr_in6 *addr6 = (conststruct sockaddr_in6*) interface->ifa_addr;

if (Inet_ntop (Af_inet6, &addr6->sin6_addr, Addrbuf, Inet6_addrstrlen)) {

Type = Ip_addr_ipv6;

}

}

if (type) {

NSString *key = [nsstringstringwithformat:@ "%@/%@", name, type];

Addresses[key] = [NSSTRINGSTRINGWITHUTF8STRING:ADDRBUF];

}

}

}

Free memory

Freeifaddrs (interfaces);

}

return [Addressescount]? Addresses:nil;

}




This is to obtain the hardware address of the network card code, if you can not compile the pass, remember to put the following these header files Add.

#include <sys/socket.h>//per MSQR
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#pragma Mark MAC Addy
Return to the local MAC Addy
Courtesy of FreeBSD Hackers Email list
Accidentally munged during previous update. Fixed to Mlamb.
-(NSString *) macaddress
{
int mib[6];
size_t Len;
Char *buf;
unsigned char *ptr;
struct IF_MSGHDR *IFM;
struct SOCKADDR_DL *sdl;

Mib[0] = ctl_net;
MIB[1] = Af_route;
MIB[2] = 0;
MIB[3] = Af_link;
MIB[4] = net_rt_iflist;

if ((mib[5] = If_nametoindex ("En0")) = = 0) {
printf ("Error:if_nametoindex error/n");
return NULL;
}

if (Sysctl (MIB, 6, NULL, &len, NULL, 0) < 0) {
printf ("Error:sysctl, Take 1/n");
return NULL;
}

if ((buf = malloc (len)) = = NULL) {
printf ("Could not allocate memory. error!/n ");
return NULL;
}

if (Sysctl (MIB, 6, buf, &len, NULL, 0) < 0) {
printf ("Error:sysctl, take 2");
return NULL;
}

IFM = (struct IF_MSGHDR *) buf;
SDL = (struct SOCKADDR_DL *) (IFM + 1);
ptr = (unsigned char *) lladdr (SDL);
NSString *outstring = [NSString stringwithformat:@ "x:x:x:x:x:x", *ptr, * (ptr+1), * (ptr+2), * (ptr+3), * (PTR+4), * (ptr+5 )];
NSString *outstring = [NSString stringwithformat:@ "xxxxxx", *ptr, * (ptr+1), * (ptr+2), * (ptr+3), * (PTR+4), * (ptr+5)];
Free (BUF);
return [outstring uppercasestring];
}

This write header file is used to obtain IP and other series functions.
#include <arpa/inet.h>
#include <netdb.h>

#include <net/if.h>

#include <ifaddrs.h>
#import <dlfcn.h>
#import "Wwanconnect.h//frome Apple, you may not have it.

#import <SystemConfiguration/SystemConfiguration.h>

There are a lot of code to get IP addresses

This is the external network visible IP address, if you are in the local area network, that is the community, not the intranet address of the LAN.

-(NSString *) whatismyipdotcom
{
Nserror *error;
Nsurl *ipurl = [Nsurl urlwithstring:@ "http://www.whatismyip.com/automation/n09230945.asp"];
NSString *ip = [NSString stringwithcontentsofurl:ipurl encoding:1 error:&error];
Return IP? IP: [Error localizeddescription];
}

This is the IP address to get the local WiFi

Matt Brown ' s get WiFi IP addy Solution
Author gave permission in cookbook under cookbook license
Http://mattbsoftware.blogspot.com/2009/04/how-to-get-ip-address-of-iphone-os-v221.html
-(NSString *) localwifiipaddress
{
BOOL success;
struct Ifaddrs * ADDRS;
const struct IFADDRS * CURSOR;

Success = Getifaddrs (&addrs) = = 0;
if (success) {
cursor = Addrs;
while (cursor!= NULL) {
The second test keeps from picking to the loopback address
if (cursor->ifa_addr->sa_family = = Af_inet && (cursor->ifa_flags & iff_loopback) = = 0)
{
NSString *name = [NSString stringwithutf8string:cursor->ifa_name];
if ([Name isequaltostring:@ "En0"])/Wi-Fi Adapter
return [NSString Stringwithutf8string:inet_ntoa ((struct sockaddr_in *) cursor->ifa_addr)];
}
cursor = cursor->ifa_next;
}
Freeifaddrs (Addrs);
}
return nil;
}

Conversion of NSString and address

+ (NSString *) stringfromaddress: (const struct SOCKADDR *) address
{
if (address && address->sa_family = = af_inet) {
const struct sockaddr_in* sin = (struct sockaddr_in*) address;
return [NSString stringwithformat:@ "%@:%d", [NSString Stringwithutf8string:inet_ntoa (SIN-&GT;SIN_ADDR)], Ntohs (sin- >sin_port)];
}

return nil;
}

+ (BOOL) addressfromstring: (NSString *) IPAddress address: (struct sockaddr_in *) address
{
if (! IPAddress | | ! [IPAddress length]) {
return NO;
}

memset ((char *) address, sizeof (struct sockaddr_in), 0);
address->sin_family = af_inet;
Address->sin_len = sizeof (struct sockaddr_in);

int conversionresult = Inet_aton ([ipaddress utf8string], &address->sin_addr);
if (Conversionresult = = 0) {
NSAssert1 (Conversionresult!= 1, @ "Failed to convert" of IP address string into a sockaddr_in:%@ ", IPAddress);
return NO;
}

return YES;
}
Get the name of the host
-(NSString *) hostname
{
Char basehostname[256]; Hi, Gunnar Larisch
int success = GetHostName (Basehostname, 255);
If (Success!= 0) return nil;
BASEHOSTNAME[255] = '/0 ';

#if Target_iphone_simulator
return [NSString stringwithformat:@ '%s ', basehostname];
#else
return [NSString stringwithformat:@ "%s.local", Basehostname];
#endif
}
Get address from Host
-(NSString *) Getipaddressforhost: (NSString *) thehost
{
struct Hostent *host = gethostbyname ([thehost utf8string]);
if (!host) {herror ("resolv"); return NULL;}
struct IN_ADDR **list = (struct in_addr * *) host->h_addr_list;
NSString *addressstring = [NSString Stringwithcstring:inet_ntoa (*list[0]) encoding:nsutf8stringencoding];
return addressstring;
}

This is the IP address of the local host
-(NSString *) localipaddress
{
struct Hostent *host = gethostbyname ([[Self hostname] utf8string]);
if (!host) {herror ("resolv"); return nil;}
struct IN_ADDR **list = (struct in_addr * *) host->h_addr_list;
return [NSString Stringwithcstring:inet_ntoa (*list[0]) encoding:nsutf8stringencoding];
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.