简体   繁体   中英

Why is HTTP request needed to get IP address in browser

I need to get the user's IP address from the browser. I know we can get device information from the browser with plain JS without any http requests involved (OS and browser info via User-Agent), but to get the IP address you need to make an HTTP request, as your browser will attaches the IP address as a header of the request so you can get it server-side or in the response of that request in the UI. I am lacking some basic understanding and I can't see why an HTTP request is required and at what point the IP address is added as a header, if the browser doesn't know how does the header get attached?

I believe OSI_model is the basic knowledge you are looking for. https://en.wikipedia.org/wiki/OSI_model

HTTP request is just the top layer of the whole network system. The IP protocol is handled on (Layer 4)Transport Layer and it will not arrived to Application Layer(Layer 7).

The statement -- "your browser will attaches the IP address as a header of the request" is Wrong .
Normally the http request doest not carry source IP information in headers. You can view the https://en.wikipedia.org/wiki/List_of_HTTP_header_fields for normal headers.

But you are right that the sever side should figure out the client's IP. How can it achieve that?
In fact HTTP is an Application Layer protocol. The topic of source IP belongs to Internet layer.
The Internet protocol suite(TCP/IP) will solve that.

Meanwhile it means it's impossible to get your ip directly in browser. Moreover, sometimes it's even impossible to get your public ip address within your System.
For example the WiFi AP normally use DHCP to assign you an private ip only. And use NAT to modify your packets when you send/receive a request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM