// setip.h
#ifndef _INCLUDE_SETIP_H_
#define _INCLUDE_SETIP_H_ // 设置IP地址 int setip(char *ip); // 获取IP地址 char* getip(char *ip_buf); #endif // end setip.h
//setip.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ioctl.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<net/if.h>
#include "setip.h"
//设置IP地址
int setip(char* ip)
{
struct ifreq temp;
struct sockaddr_in *addr;
int fd = 0;
int ret = -1;
strcpy(temp.ifr_name, "eth0");
if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
{
return -1;
}
addr = (struct sockaddr_in *)&(temp.ifr_addr);
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = inet_addr(ip);
ret = ioctl(fd, SIOCSIFADDR, &temp);
close(fd);
if(ret < 0)
return -1;
return 0;
}
// 获取IP地址
char* getip(char* ip_buf)
{
struct ifreq temp;
struct sockaddr_in *myaddr;
int fd = 0;
int ret = -1;
strcpy(temp.ifr_name, "eth0");
if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
{
return NULL;
}
ret = ioctl(fd, SIOCGIFADDR, &temp);
close(fd);
if(ret < 0)
return NULL;
myaddr = (struct sockaddr_in *)&(temp.ifr_addr);
strcpy(ip_buf, inet_ntoa(myaddr->sin_addr));
return ip_buf;
}
int main(int argc, char * argv[])
{
char * ip = "172.20.223.117";
char buf[16]="";
setip(argv[1]);
printf("ipaddr=%s/n",getip(buf));
return 0;
}
// end setip.c