- 論壇徽章:
- 0
|
本帖最后由 liuhengloveyou 于 2010-02-25 09:01 編輯
- #include <sys/socket.h>
- #include <unistd.h>
- #include <net/if.h>
- #include <string.h>
- #include <stdio.h>
- #include <linux/sockios.h>
- #include <arpa/inet.h>
- #define BUFSIZE 16
- /*
- * 獲得指定網(wǎng)口的IP
- */
- int get_inetip(char *in_name, char *buf)
- {
- int socket_fd;
- struct ifreq ifr;
- struct ifconf conf;
- if ((socket_fd = socket(AF_INET,SOCK_DGRAM,0)) == -1) {
- perror("socket error!\n");
- return -1;
- }
- strcpy(ifr.ifr_name, in_name);
-
- if(ioctl(socket_fd,SIOCGIFADDR,&ifr) < 0) {
- perror("ioctl error\n");
- return -1;
- }
-
- strcpy(buf, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr));
- return 0;
- }
- int main(void)
- {
- char buff[BUFSIZE];
- get_inetip("eth0", buff);
- printf("%s\n", buff);
-
- return 0;
- }
復(fù)制代碼 昨天要這功能, 論壇里沒(méi)找到很好的實(shí)現(xiàn), 就自己實(shí)現(xiàn)了個(gè). 比較簡(jiǎn)單. |
|