在linux下 获取,修改本机IP地址的两个函数

1 篇文章 0 订阅

//获取本机IP地址函数

[cpp]  view plain copy
  1.  #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
     #include <sys/socket.h>
     #include <netinet/in.h>
     #include <arpa/inet.h>
     #include <sys/types.h>
     #include <sys/ioctl.h>
     #include "linux/if.h"

  2. void GetLocalIp()  
  3. {  
  4.   
  5.     int sock_get_ip;  
  6.     char ipaddr[50];  
  7.   
  8.     struct   sockaddr_in *sin;  
  9.     struct   ifreq ifr_ip;     
  10.   
  11.     if ((sock_get_ip=socket(AF_INET, SOCK_STREAM, 0)) == -1)  
  12.     {  
  13.          printf("socket create failse...GetLocalIp!/n");  
  14.          return "";  
  15.     }  
  16.      
  17.     memset(&ifr_ip, 0, sizeof(ifr_ip));    
  18.     /*根据自己的端口更改eth*/
  19.     strncpy(ifr_ip.ifr_name, "eth0"sizeof(ifr_ip.ifr_name) - 1);     
  20.    
  21.     if( ioctl( sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0 )     
  22.     {     
  23.          return "";     
  24.     }       
  25.     sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;     
  26.     strcpy(ipaddr,inet_ntoa(sin->sin_addr));         
  27.       
  28.     printf("local ip:%s /n",ipaddr);      
  29.     close( sock_get_ip );  
  30.       
  31.     return ipaddr;  
  32. }  
  

//修改本机IP地址的函数

  1. int SetLocalIp( const char *ipaddr )  
  2. {  
  3.   
  4.     int sock_set_ip;  
  5.       
  6.     struct sockaddr_in sin_set_ip;  
  7.     struct ifreq ifr_set_ip;  
  8.   
  9.     bzero( &ifr_set_ip,sizeof(ifr_set_ip));  
  10.    
  11.     if( ipaddr == NULL )  
  12.         return -1;  
  13.   
  14.     if(sock_set_ip = socket( AF_INET, SOCK_STREAM, 0 ) == -1);  
  15.     {  
  16.         perror("socket create failse...SetLocalIp!/n");  
  17.         return -1;  
  18.     }  
  19.    
  20.     memset( &sin_set_ip, 0, sizeof(sin_set_ip));  
  21.     strncpy(ifr_set_ip.ifr_name, "eth0"sizeof(ifr_set_ip.ifr_name)-1);     
  22.       
  23.     sin_set_ip.sin_family = AF_INET;  
  24.     sin_set_ip.sin_addr.s_addr = inet_addr(ipaddr);  
  25.     memcpy( &ifr_set_ip.ifr_addr, &sin_set_ip, sizeof(sin_set_ip));  
  26.   
  27.     if( ioctl( sock_set_ip, SIOCSIFADDR, &ifr_set_ip) < 0 )  
  28.     {  
  29.         perror( "Not setup interface/n");  
  30.         return -1;  
  31.     }  
  32.   
  33.     //设置激活标志  
  34.     ifr_set_ip.ifr_flags |= IFF_UP |IFF_RUNNING;  
  35.   
  36.     //get the status of the device  
  37.     if( ioctl( sock_set_ip, SIOCSIFFLAGS, &ifr_set_ip ) < 0 )  
  38.     {  
  39.          perror("SIOCSIFFLAGS");  
  40.          return -1;  
  41.     }  
  42.   
  43.     close( sock_set_ip );  
  44.     return 0;  
  45. (转自:http://blog.csdn.net/davidge333/article/details/5250566

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值