Linux网络配置代码
http://blog.csdn.net/myaccella/article/details/6968753
Linux下 配置网络接口比较简单, IP地址,掩码,缺省网管用ioctl,DNS直接操作/etc/resolv.conf文件就可以了。
- void interface_configure(const char* address,
- const char* netmask,
- const char* gateway,
- const char* dns1, const char* dns2)
- {
- ifreq ifr;
- sockaddr_in saddr;
- rtentry rte;
- sockaddr_in rtdst;
- sockaddr_in rtgw;
- char buffer[1024];
- int fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (fd == -1) {
- fprintf(stderr,"Failed to create socket: %s", strerror(errno));
- return;
- }
- // Following operation eq. to 'ifconfig eth0 <address> netmask <netmask>'
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
- memset(&saddr, 0, sizeof(saddr));
- saddr.sin_family = AF_INET;
- inet_aton(address, &saddr.sin_addr);
- memcpy(&ifr.ifr_addr, &saddr, sizeof(saddr));
- if (ioctl(fd, SIOCSIFADDR, &ifr) == -1) {
- fprintf(stderr, "Failed to set interface address %s: %s",
- address, strerror(errno));
- return;
- }
- inet_aton(netmask, (sockaddr_in*)(&(ifr.ifr_netmask.sin_addr));
- if (ioctl(fd, SIOCSIFNETMASK, &ifr) == -1) {
- fprintf(stderr, "Failed to set interface netmask %s: %s",
- netmask, strerror(errno));
- return;
- }
- // route del default
- memset(&rte, 0, sizeof(rte));
- rte.rt_flags = RTF_UP | RTF_GATEWAY;
- memset(&rtdst, 0, sizeof(rtdst));
- rtdst.sin_family = AF_INET;
- memcpy(&rte.rt_dst, &rtdst, sizeof(rtdst));
- while (1) {
- if (::ioctl(fd, SIOCDELRT, &rte) == -1) {
- if (errno != ESRCH) {
- fprintf(stderr, "Failed to delete gateway: %s", strerror(errno));
- }
- break;
- }
- }
- // route add default gw <gatevay>
- memset(&rtgw, 0, sizeof(rtgw));
- rtgw.sin_family = AF_INET;
- inet_aton(gateway, &rtgw.sin_addr);
- memcpy(&rte.rt_gateway, &rtgw, sizeof(rtgw));
- if (ioctl(fd, SIOCADDRT, &rte) == -1) {
- fprintf(stderr, "Failed to add gateway %s: %s",
- gateway, strerror(errno));
- }
- close(fd);
- // echo nameserver <dns1> > /etc/resolv.conf
- // echo nameserver <dns2> >> /etc/resolv.conf
- fd = creat("/etc/resolv.conf", 0666);
- if (fd == -1) {
- fprintf(stderr, "Failed to open /etc/resolv.conf %s", strerror(errno));
- }
- else {
- if (dns1 != NULL) {
- snprintf(buffer, sizeof(buffer), "nameserver %s\n", dns1);
- write(fd, buffer, strlen(buffer));
- }
- if (dns2 != NULL) {
- snprintf(buffer, sizeof(buffer), "nameserver %s\n", dns2);
- write(fd, buffer, strlen(buffer));
- }
- close(fd);
- }
- }