I know there are APIs for doing so but I want to do so as cheaply and locally as possible(without compromising on on quality of guesses ).
For a local solution, you can use a database file. You can find free ones with virtually limited accuracy below:
There exists paying variants with better accuracy. However, when using a local database file, you should ask yourself some questions:
If the answer is No to one of the previous questions, you should most probably use an IP Geolocation API. I suggest having a look at my service, Ipregistry: it is fast, reliable and inexpensive.