이 튜토리얼에서는 프로그래밍 방식으로 안드로이드 기기의 IP 주소를 가져오는 방법을 단계별로 살펴봅니다. Wi-Fi에 연결된 기기라면 WifiManager와 Formatter 클래스를 활용해 몇 줄의 코드만으로 현재 IP 주소를 손쉽게 확인할 수 있습니다.
구현 단계
1단계 — 새 프로젝트 생성
Android Studio를 실행한 뒤 File ⇒ New Project 메뉴로 이동하고, 새 프로젝트 생성에 필요한 세부 정보를 모두 입력해 프로젝트를 만듭니다.
2단계 — 레이아웃 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 IP 주소를 표시할 TextView 하나를 배치하는 구성입니다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <TextView android:id="@+id/getIPAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="IP address of your Device" android:textStyle="bold" android:textSize="25sp" /> </RelativeLayout>
3단계 — MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다. WifiManager로 연결 정보를 조회한 뒤, Formatter.formatIpAddress()를 사용해 정수형 IP 값을 사람이 읽을 수 있는 문자열로 변환합니다.
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.getIPAddress);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ipAddress = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
textView.setText("Your Device IP Address: " + ipAddress);
}
}
4단계 — 매니페스트에 권한 추가
Wi-Fi 상태 정보에 접근하려면 매니페스트에 권한 선언이 반드시 필요합니다. androidManifest.xml 파일에 아래와 같이 ACCESS_WIFI_STATE 권한을 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같이 해당 기기의 IP 주소가 표시되는 것을 확인할 수 있습니다.

알아두면 좋은 팁
- 권한 관련: ACCESS_WIFI_STATE는 일반(normal) 권한에 해당하므로, 매니페스트에 선언하기만 하면 되고 별도의 런타임 권한 요청은 필요하지 않습니다.
- 네트워크 연결 필수: 기기가 Wi-Fi에 연결되어 있지 않으면 유효한 IP 대신 "0.0.0.0"이 반환될 수 있으므로, 실행 전 네트워크 연결 상태를 먼저 확인하는 것이 좋습니다.
- 지원 중단(deprecated) API 주의: Formatter.formatIpAddress()는 현재 공식적으로 지원 중단된 API입니다. 최신 프로젝트에서는 아래처럼 NetworkInterface를 사용하는 방식을 권장합니다.
private String getLocalIpAddress() {
try {
for (java.util.Enumeration<java.net.NetworkInterface> en =
java.net.NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
java.net.NetworkInterface intf = en.nextElement();
for (java.util.Enumeration<java.net.InetAddress> enumIpAddr =
intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
java.net.InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
android.util.Log.e("IP Address", ex.toString());
}
return null;
}