主要通过Socket sockaddr_in结构体实现网络的配置
部分源码:
1、setip_host.cpp
int setHostIp(char *netdev,char *ipaddr) { struct sockaddr_in sin; struct ifreq ifr; int sock;
int ret; char *ptr; short found_colon=0;
bzero(&ifr,sizeof(struct ifreq)); if(netdev ==NULL) return (-1); if (ipaddr==NULL) return (-1); sock=socket(AF_INET,SOCK_DGRAM,0); if (sock== -1) { perror( "Not create network socket connection\n "); //return (-1);
}
strncpy(ifr.ifr_name,netdev,IFNAMSIZ); ifr.ifr_name[IFNAMSIZ-1]=0; memset(&sin,0,sizeof(sin)); sin.sin_family=AF_INET; sin.sin_addr.s_addr=inet_addr(ipaddr); memcpy(&ifr.ifr_addr,&sin,sizeof(sin));
if (ioctl(sock,SIOCSIFADDR,&ifr)<0) { perror( "Not setup interface\n "); //return (-1);
}
//ifr.ifr_flags |=IFF_UP | IFF_RUNNING;
if(ioctl(sock,SIOCSIFFLAGS,&ifr)<0) { perror( "SIOCSIFFLAGS "); //return (-1);
} return (0); }
|
2、getip_host.cpp
void getHostIp(char* netDev, char*ipaddress) { int sock; struct sockaddr_in sin; struct ifreq ifr;
sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { perror("socket"); //return -1;
}
strncpy(ifr.ifr_name, netDev, IFNAMSIZ); ifr.ifr_name[IFNAMSIZ - 1] = 0;
if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) { perror("ioctl"); //return -1;
}
memcpy(&sin, &ifr.ifr_addr, sizeof(sin)); sprintf(ipaddress, "%s", inet_ntoa(sin.sin_addr)); //return sin.sin_addr;
//return 0;
}
|
|
文件: |
c_netconfig.zip |
大小: |
21KB |
下载: |
下载 | |
阅读(630) | 评论(0) | 转发(0) |