我正在尝试从DHCP server请求特定的IP地址。
我的理解是,如果服务器在初始DHCP_DISCOVER消息中支持DHCP_REQUESTED_IP请求,我应该能够这样做。
以下是我的代码无效:
ip_addr_copy(&dhcp->msg_out->ciaddr , "0xc0a80014" );
dhcp->msg_out->yiaddr.addr = 0xc0a801e0 ;
dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4);
dhcp_option_long(dhcp, htonl(0xc0a80176));
dhcp_option_long(dhcp, htonl(0xc0a801e0));
dhcp_option(dhcp, DHCP_OPTION_SERVER_ID, 4);
dhcp_option_long(dhcp, htonl(0xc0a80164));
dhcp_option_long(dhcp, htonl(0xc0a80101));
dhcp_option(dhcp, DHCP_OPTION_PARAMETER_REQUEST_LIST, 4/*num options*/);
答案 0 :(得分:1)
根据我的假设,当时发现开始dhcp
,您需要IP地址。
现在,例如。
如果使用udhcpc
(busybox:udhcp客户端与DHCP服务器协商租约,并在获得或丢失租约时通知一组脚本。)* 我发现ip on接口wlan0然后我首先在系统调用下面写,以便在wlan0
system("udhcpc -i wlan0")
然后致电
GetIpAddress_system(ipaddress);//for getting ip address
如此简单的代码
char ipaddress[16];
system("udhcpc -i wlan0")
GetIpAddress_system(ipaddress);//for getting ip address
printf("\nip address:%s",ipaddress);
找到GetIpAddress_system()
的来源,如下所示
static int GetIpAddress_system(char *myIp)
{
int retVal=0;
int size = 1;
struct ifreq *ifr;
struct ifconf ifc;
struct sockaddr_in sa;
char ip_add[24]={0};
int serversocket; /* Socket */
#define inaddrr(x) (*(struct in_addr *) &ifr->x[sizeof sa.sin_port])
#define IFRSIZE ((int)(size * sizeof (struct ifreq)))
/* Create socket for receiving */
if ((serversocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
printf("socket() failed");fflush(stdout);
return -1;
}
else
{
ifc.ifc_len = IFRSIZE;
ifc.ifc_req = NULL;
do
{
++size;
/* realloc buffer size until no overflow occurs */
if (NULL == (ifc.ifc_req = realloc(ifc.ifc_req, IFRSIZE)))
{
retVal= -1;
break;
}
ifc.ifc_len = IFRSIZE;
if (ioctl(serversocket, SIOCGIFCONF, &ifc))
{
perror("ioctl SIOCFIFCONF");
retVal = -1;
break;
}
}while(IFRSIZE <= ifc.ifc_len);
if(0 == retVal)
{
ifr = ifc.ifc_req;
for (;(char *) ifr < (char *) ifc.ifc_req + ifc.ifc_len; ++ifr)
{
if (ifr->ifr_addr.sa_data == (ifr+1)->ifr_addr.sa_data)
{
continue; /* duplicate, skip it */
}
if (ioctl(serversocket, SIOCGIFFLAGS, ifr))
{
continue; /* failed to get flags, skip it */
}
if(strcmp(ifr->ifr_name,"wlan0") == 0)
{
strncpy(ip_add,inet_ntoa(inaddrr(ifr_addr.sa_data)),sizeof(ip_add));
break;
}
}
}
close(serversocket);
}
if(0 == retVal)
{
printf("%s\n",ip_add);
if(myIp)
{
memset(myIp,0,15);
snprintf(myIp,15,"%s",ip_add);
}
if(ip_add[0])
{
return 0;
}
else
{
return -1;
}
}
else
{
return -1;
}
}