iphone 获得本机IP地址

#include <unistd.h>

#include <netdb.h>

#include <arpa/inet.h>

#include <string.h>

char baseHostName[255];

gethostname(baseHostName, 255); // 获得本机名字

 

struct hostent *host = gethostbyname(baseHostName); // 将本机名字转换成主机网络结构体 struct hostent

 

if (host == NULL) {

herror("resolv");

}

else {

struct in_addr **list = (struct in_addr **)host->h_addr_list;

char ip[255];

strcpy(ip, inet_ntoa(*list[0])); // 获得本机IP地址

// printf("IP: %s", ip);

NSString *ipAddress = [[NSString allocinitWithCString:ip];

NSLog(@"%@", ipAddress); // 打印本机IP地址

[ipAddress release];

}

posted @ 2012-08-18 12:04  careerman  阅读(322)  评论(0编辑  收藏  举报