Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current computer's IP address in Xcode

When testing iPhone apps that connect to my local machine's server, I need to enter my computer's local IP address as opposed to localhost in order to test with devices other than the simulator. This gets annoying with dynamic IP addresses and when multiple developers are testing. Is there a code snippet that can get the IP address of the computer that is compiling code, and NOT the IP the address of the device that the application is running on (preferably in C or Objective-C, and not Swift)?

like image 816
Mike V Avatar asked Jan 29 '15 15:01

Mike V


2 Answers

1) Add a "Run Script" in the "Build Phases" tab of your Xcode project that contains this:

export SERVER_IP=`ipconfig getifaddr en0`

Note: change "en0" to whichever interface matches your machine. en0 is the wifi on my machine and my hard-wire is en3. Do an "ifconfig -a" in Terminal to get the list of all of your adapters and see which is which for your machine

2) Go to your project file. Click the Project itself in the left menu then Build Settings in the right side. Go to "Apple LLVM 6.0 - Custom Compiler Flags". Under "Other C Flags" -> "Debug" define a new value called -DSERVER_IP=${SERVER_IP}

This will map your build script's results into a #DEFINE in your project

3) In your code use SERVER_IP just like you would any other #DEFINE and it will always have the value of the computer that built the code.

like image 70
Chris Morse Avatar answered Nov 15 '22 12:11

Chris Morse


I got this working by having a run script set the computer's IP address in the app's plist, then reading the plist value in code.

1) In your Info.plist file, add a key/value pair that will contain your computer's IP address. For this example, we'll add a key of "CompanyNameDevServerIP", of type "String". Note that this key/value pair should be prefixed uniquely, so that it doesn't conflict with Apple's keys (see here for more info).

2) In the "Build Phases" tab, add a run script that contains the following:

if [ "$CONFIGURATION" == "Debug" ]; then
  echo -n ${TARGET_BUILD_DIR}/${INFOPLIST_PATH} | xargs -0 /usr/libexec/PlistBuddy -c "Set :CompanyNameDevServerIP `ipconfig getifaddr en0`"
else
  echo -n ${TARGET_BUILD_DIR}/${INFOPLIST_PATH} | xargs -0 /usr/libexec/PlistBuddy -c "Delete :CompanyNameDevServerIP"
fi

This sets the computer's IP address in the plist that gets bundled with the build, but only in debug builds. (It's removed from the plist file in release builds.)

  • Hat tip to this blog post for providing this technique.
  • You may need to use a different interface other than en0 (see here for more info).

3) In code, retrieve this plist value to get your computer's IP address:

NSString *serverIP = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CompanyNameDevServerIP"];
like image 39
Jed Lau Avatar answered Nov 15 '22 13:11

Jed Lau