在實際的項目運用中,我們往往需要綁定本機的IP和端口號,或者作爲服務器需要將自己的IP信息更新至數據庫中,便於其他其中通過查詢數據庫得到地址從而發數據,如果我們把它做成智能的獲取本機的IP,這樣我們的代碼的可移植性就提高了。下面就介紹一種在windows和linux下面可以智能獲取我們本機的局域網IP的方法,不妥之處還請大家多多指教。
(1)Windows
#include "winsock2.h"
#pragma comment(lib, "ws2_32.lib")
int GetLocalIP(char *ip)
{
WSADATA wsaData;
char name[155];
PHOSTENT hostinfo;
if (WSAStartup(MAKEWORD(2, 0), &wsaData) == 0)
{
if (gethostname(name, sizeof(name)) == 0)
{
if ((hostinfo = gethostbyname(name)) != NULL)
{
ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list);
printf("local ip : %s\n", ip);
}
}
WSACleanup();
}
return 1;
}
int main(int argc, char argv[])
{
char getip[64] = { 0 };
GetLocalIP(getip);
return 0;
}
(2)Linux
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include<string.h>
#include <sys/ioctl.h>
#include <linux/if.h>
int GetLocalIP(char *ip)
{
int MAXINTERFACES = 16;
int fd, intrface = 0;
struct ifreq buf[MAXINTERFACES]; ///if.h
struct ifconf ifc; ///if.h
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) //socket.h
{
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t)buf;
if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc)) //ioctl.h
{
intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-- > 0)
{
if (!(ioctl(fd, SIOCGIFADDR, (char *)&buf[intrface])))
{
sprintf(ip, "%s", inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
printf("ip:%s\n", ip);
break;
}
}
}
close(fd);
}
return 0;
}
該程序可以直接運行,已經在兩個平臺中測試驗證通過!!!