如何用c程序获得本机IP地址?

请指教!谢谢
---------------------------------------------------------------

#include

 1<stdio.h>   
 2#include <sys types.h="">   
 3#include <sys socket.h="">   
 4#include <sys ioctl.h="">   
 5#include <netinet in.h="">   
 6#include <net if.h="">   
 7#include <net if_arp.h="">   
 8#include <arpa inet.h="">   
 9#include <errno.h>   
10  
11#define ETH_NAME "eth0"   
12  
13int main()   
14{   
15int sock;   
16struct sockaddr_in sin;   
17struct ifreq ifr;   
18  
19sock = socket(AF_INET, SOCK_DGRAM, 0);   
20if (sock == -1)   
21{   
22perror("socket");   
23return -1;   
24}   
25  
26strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);   
27ifr.ifr_name[IFNAMSIZ - 1] = 0;   
28  
29if (ioctl(sock, SIOCGIFADDR, 𝔦) &lt; 0)   
30{   
31perror("ioctl");   
32return -1;   
33}   
34  
35memcpy(&amp;sin, &amp;ifr.ifr_addr, sizeof(sin));   
36fprintf(stdout, "eth0: %s\n", inet_ntoa(sin.sin_addr));   
37  
38return 0;   
39}</errno.h></arpa></net></net></netinet></sys></sys></sys></stdio.h>
Published At
Categories with 服务器类
Tagged with
comments powered by Disqus