You want to authenticate the connection via IP?
This type of block is called ACL or Access Control Lists and only serves to bar the majority of lay users.
Access Control Lists (ACL) allow or deny traffic from specific IP addresses to a specific IP address and destination port. It also allows specifying different types of traffic, such as ICMP, TCP, UDP, etc.
Must be implemented in the router and not in the code, client or server.
It should not be the only authentication criterion, this type of protection only works as dam apparatus for the large mass of lay users. It does not work with specialized attackers as it is 100% susceptible to a Host Header Attack, which consists of planting false information in requests, in case the attacker generates a series of false requests each with a different IP thus formed a table with the ips accepted and rejected by the ACL .
It is kind of validation used to block the annoying "uncle" who wants to steal Wifi at the party but that does not stop his neighbor’s son, 10 years, to steal his internet connection.
The two answers plus the question code cannot offer any certainty about the veracity of the delivered IP as they can be circumvented with a line of code using the developer’s own browser tool.
If you want to authenticate the communication suggest two models, Session-Based Authentication and the Token-Based Authentication.
Session-Based Authentication
In Session-Based Authentication, the server will create a session for the user after logging in.
The session ID is stored in a cookie in the user’s browser. As long as the user remains logged in, the cookie will be sent along with all subsequent requests.
The server can then compare the session ID stored in the cookie with the session information stored in the memory to verify the user’s identity and send a reply to the corresponding state.
Token-Based Authentication
Many web applications use JSON Web Token (JWT) instead of sessions for authentication. In the token-based application, the server creates the JWT with a secret and sends the JWT to the client. The client stores the JWT (usually in local storage) and includes the JWT in the header for each request. The server would validate JWT with all client requests and send a response.
The biggest difference is that the user’s state is not stored on the server, as the state is stored inside the token on the client side. Most modern web applications use JWT for authentication for reasons that include mobile device scalability and authentication.
What exactly are you trying to do?
– Woss
@web_charles if it is a critical validation that cannot be circumvented, it should be done via PHP. And it’s not an "internal fault", the server will get the gateway from your router even, unless you use Ipv6 or have Ipv4 valid on each device. Now if you want to validate an internal equipment of a network via server, via IP does not give, the correct one would be a login and password, a token, etc.
– Leonardo Getulio