Skip to main content
richardh
Associate III
June 3, 2020
Question

LWIP - Read my IP address

  • June 3, 2020
  • 11 replies
  • 15628 views

I have found examples online searching under LWIP such as

// What is our current IP address?
//
ulIPAddr = lwIPLocalIPAddrGet();

but I cannot find the function in the source code, or any other reference to reading my IP address. I would like to be able to read it regardless of whether I'm static or DHCP.

This topic has been closed for replies.

11 replies

richardh
richardhAuthor
Associate III
June 3, 2020

Okay, so with a little more hunting, I have

 extern struct netif gnetif;
 
 local_IP = gnetif.ip_addr.addr;
 
printf("IP %d.%d.%d.%d\n\r",(local_IP & 0xff), ((local_IP >> 8) & 0xff), ((local_IP >> 16) & 0xff), (local_IP >> 24));

but if its DHCP, how do I know if the address is initialised?

Piranha
Principal III
June 3, 2020

To get IP address, use netif_ip4_addr() and ip4_addr_get_u32(). When using DHCP, use ip4_addr_isany_val() to determine if it's assigned. And take a look at lwIP's bunch of similar functions and macros.

richardh
richardhAuthor
Associate III
June 4, 2020

Thats spot on - thank you!

More questions though, how do I read the subnet mask and MAC address also?

Finally can I set the host name manually as well? so if I look at the DHCP server reservations pool I can easily spot my device by name?

richardh
richardhAuthor
Associate III
June 5, 2020

as an addition, how do I set the MAC Address?

I can find it hardcoded in ethernet.c which is fine if this was going to be a single unit, but if by some miracle it went into production then what is the mechanism to allow you to update it?

Host name I have figured out, I was just reading it wrong.

 extern struct netif gnetif;
 
 local_SubNet = ip4_addr_get_u32(netif_ip4_netmask(&gnetif));
 
 local_Gateway = ip4_addr_get_u32(netif_ip4_gw(&gnetif));

Piranha
Principal III
August 28, 2022

> I can find it hardcoded in ethernet.c which is fine if this was going to be a single unit, but if by some miracle it went into production then what is the mechanism to allow you to update it?

Then you write a normal code, which updates the MAC address in both - the ETH registers and NETIF structure.

FPaul.3
Visitor II
August 24, 2022

Credit to GitHub copilot, which recommends me: 

printf("IP address: %s\n", ip4addr_ntoa(&gnetif.ip_addr));

result:

IP address: 192.168.1.63

Piranha
Principal III
August 28, 2022

More correct version:

printf("IP address: %s\n", ip4addr_ntoa(netif_ip4_addr(&gnetif)));

Pavel A.
August 28, 2022

> Credit to GitHub copilot

Few years ago when I first seen the Cube, I hoped it would evolve in the direction of the Copilot: a tool that knows all the reference manuals, all errata, trained on all the examples, backed by a serious AI. Alas.