본문 바로가기
개발

안드로이드 에뮬레이터에서 로컬호스트 주소 접근 방법

by 마스터누누 2019. 7. 1.
728x90
반응형

Retrofit2를 사용하기 위해 node 서버를 로컬에 띄웠는데 접근이 되지 않는다.

디바이스의 경우 실행 환경이 다르기 때문에 루프백 주소(127.0.0.1)로 접근하는건 말이 안되고,

에뮬레이터에서 루프백 주소로 접근했더니, 그래도 동작 불능이다.

 

구글링을 했더니 역시나 해답 발견.

안드로이드는 가상 라우터와 방화벽 뒤에서 네트워크가 동작하기 때문에 locahost나 127.0.0.1이 에뮬레이터를 실행하는 컴퓨터가 아니라 에뮬레이터 자신이 되어버린다는것.

따라서 불변의 접근 가능한 주소를 제공해준다.

 

주소는 다음과 같다.

AVD - 10.0.2.2
Genymotion - 10.0.3.2

 

코드에 적용하면 다음과 같이 사용할 수 있겠다.

 

public class Repo {
    private static final String URL = "http://10.0.2.2:3000";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build());

    private static Retrofit retrofit = builder.build();

    public static <S> S createService(Class<S> serviceClass) {
        return retrofit.create(serviceClass);

    }
}

 

아래에 원문을 남겨 놓는다.

https://jsdev.kr/t/tip-avd-ip/1023

반응형

댓글