2 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 #include <gpxe/dhcp.h>
24 #include <gpxe/async.h>
25 #include <gpxe/netdevice.h>
26 #include <usr/ifmgmt.h>
27 #include <usr/dhcpmgmt.h>
36 * Configure network device via DHCP
38 * @v netdev Network device
39 * @ret rc Return status code
41 int dhcp ( struct net_device *netdev ) {
42 static struct dhcp_option_block *dhcp_options = NULL;
43 struct dhcp_session dhcp;
44 struct in_addr address = { htonl ( 0 ) };
45 struct in_addr netmask = { htonl ( 0 ) };
46 struct in_addr gateway = { INADDR_NONE };
50 /* Check we can open the interface first */
51 if ( ( rc = ifopen ( netdev ) ) != 0 )
54 /* Free up any previously-acquired options */
56 unregister_dhcp_options ( dhcp_options );
57 free_dhcp_options ( dhcp_options );
61 /* Clear any existing routing table entry */
62 del_ipv4_address ( netdev );
64 /* Issue DHCP request */
65 printf ( "DHCP (%s %s)...", netdev->name, netdev_hwaddr ( netdev ) );
66 memset ( &dhcp, 0, sizeof ( dhcp ) );
68 async_init_orphan ( &async );
69 if ( ( rc = start_dhcp ( &dhcp, &async ) ) != 0 ) {
70 printf ( "could not start (%s)\n", strerror ( rc ) );
73 async_wait ( &async, &rc, 1 );
75 printf ( "failed (%s)\n", strerror ( rc ) );
80 /* Store and register options */
81 dhcp_options = dhcp.options;
82 register_dhcp_options ( dhcp_options );
84 /* Retrieve IP address configuration */
85 find_dhcp_ipv4_option ( dhcp_options, DHCP_EB_YIADDR, &address );
86 find_dhcp_ipv4_option ( dhcp_options, DHCP_SUBNET_MASK, &netmask );
87 find_dhcp_ipv4_option ( dhcp_options, DHCP_ROUTERS, &gateway );
89 /* Set up new IP address configuration */
90 if ( ( rc = add_ipv4_address ( netdev, address, netmask,
92 printf ( "Could not configure %s with DHCP results: %s\n",
93 netdev->name, strerror ( rc ) );