linux C 获取与修改IP地址

主要有两种方法:


一种是用system执行shell命令,如:

system("ifconfig usb0 192.168.1.188");  

  
另一种用ioctl系统调用:

int usb_chann_setip(char *ip)
{
	struct ifreq temp;
	struct sockaddr_in *addr;
	int fd = 0;
	int ret =-1;

	strcpy(temp.ifr_name, "usb0");


	if((fd = socket(AF_INET, SOCK_STREAM, 0))<0){
		++usb_info.setip_socket_open_failed;
		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){
		++usb_info.setip_socket_ioctl_failed;
		return -1;
	}

	return 0;
}

char *usb_chann_getip(char *ip_buf)
{
	struct ifreq temp;
	struct sockaddr_in *myaddr;
	int fd = 0;
	int ret =-1;

	strcpy(temp.ifr_name, "usb0");

	if ((fd = socket(AF_INET, SOCK_STREAM, 0))<0){
		++usb_info.getip_socket_open_failed;
		return NULL;
	}

	ret = ioctl(fd, SIOCGIFADDR, &temp);
	close(fd);

	if (ret < 0){
		++usb_info.getip_socket_ioctl_failed;
		return NULL;
	}

	myaddr = (struct sockaddr_in *)&(temp.ifr_addr);
	strcpy(ip_buf, inet_ntoa(myaddr->sin_addr));

	return ip_buf;
}



posted on 2014-07-01 16:00  疯子123  阅读(734)  评论(0编辑  收藏  举报

导航