理论已经说完了,先说说,如果获取IP地址:
直接实例如下:
1 /*------------------------------------------------------------------
2 - Filename : getIpMacMask.c
3 - CreateTime : 2021-12-21 17:33
4 - Author : mkx
5 - Description : get local ip
6 ------------------------------------------------------------------*/
7 #include <stdio.h>
8 #include <string.h>
9 #include <sys/socket.h>
10 #include <arpa/inet.h>
11 #include <net/if.h>
12 #include <sys/ioctl.h>
13 #include <unistd.h>
14
15 #define IF_NAME "ens33" //network port
16
17 /*************************************
18 * @Function : get_ip
19 * @param :
20 * ifname : network port
21 * ip : store data
22 * @Description : get local ip
23 *************************************/
24 int get_ip(char *ifname,char *ip)
25 {
26 char *temp = NULL;
27 int inet_sock;
28 struct ifreq ifr;
29
30 inet_sock = socket(AF_INET,SOCK_DGRAM,0);
31
32 memset(ifr.ifr_name,0,sizeof(ifr.ifr_name));
33 memcpy(ifr.ifr_name,ifname,strlen(ifname));
34
35 if(0 != ioctl(inet_sock,SIOCGIFADDR,&ifr))
36 {
37 perror("ioctl error!");
38 return 1;
39 }
40
41 temp = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
42 memcpy(ip,temp,strlen(temp));
43
44 close(inet_sock);
45
46 return 0;
47
48 }